multiline: Indent solution does not match examples in proposals.
Reinier Zwitserloot
reinier at zwitserloot.com
Wed Feb 28 06:10:42 UTC 2018
Some feedback on multiline string literals. Where 'proposal' is referenced,
it refers to: https://bugs.openjdk.java.net/browse/JDK-8196004
# Indents; proposed solution does not match shown examples
The proposal contains a multiline example in there showing off some HTML.
The HTML is indented. The 'traditional' (left side) view keeps the
HTML-relevant indents: If you were to print the shown literal it would look
like nicely formatted HTML. The right hand side ('raw string literal')
shows something that couldn't possibly result in the string on the left,
unless the compiler knows the size of a tabstop which it should never have
to know. Later on the proposal suggests not trying to be smart about
indents and saving ALL whitespace, offering the solution of adding a method
to strings to trim it away.
You can't make that method. At best you can strip all whitespace after
newlines but that still wouldn't get you the string on the left: That would
get you a flattened structure; HTML where each line has no leading
whitespace. It wouldn't be nicely formatted. It wouldn't be equal to the
'traditional' string on the left.
One way out is to state that the leading whitespace on the very first line
of the multiline literal is considered the code indent, and it is
eliminated from the first and all other lines; it is a compiler error if
subsequent lines don't have at least the same indent. This does require the
multiline string to start on a new line:
example (usage of braces intentional in case this won't render well in your
mail reader if I use actual HTML tags):
String html = "
{html}
{head}...
{/html}";
Going with the above solution would imply it is not possible to have
multiline string literals with leading whitespace in them, but that is far
more rare in my opinion than the need for string literals where some sort
of sensible indentation remains part of the string literal. You can still
make strings with leading whitespace by constructing them: String
withLeading = " \t \n " + `... multiline string here ... `.
Going with the actual proposal, you're forced to write:
String html = "{html}
{head}...
{/html}";
This doesn't look good as a snippet, let alone as part of a larger source
file. The existence of a strip-whitespace-per-line method would also be
confusing, in that it wouldn't get you what the 'traditional' example shows
you. Considering that the example gets this wrong, I'll take it the notion
that it's confusing is amply proven.
--Reinier Zwitserloot
More information about the amber-dev
mailing list