String reboot proposal
Victor Nazarov
asviraspossible at gmail.com
Wed Apr 17 02:19:06 UTC 2019
I want to propose one more design vector for enhanced string literals that
I haven't seen before
Basically, I propose two extensions to get to multiline literals with
incidental white space handling.
Extension1: allow sequences of string literals to denote a single
concatenated literal
Extension2: allow string literals that spans from an opening token till the
end of a line
Let's start with an example:
String j = ""
+ "public static void " + name + "(String... args) {\n"
+ " System.out.println(\"Hello,\\t\" +
String.join(args));\n"
+ "}\n";
Extension1: allow sequence of string literals to denote concatenated literal
With this extension we can get rid of plus operators, like this:
String j = ""
"public static void " + name + "(String... args) {\n"
" System.out.println(\"Hello,\\t\" + String.join(args));\n"
"}\n";
This feature is not so alien, it is present in C language.
It may seem not worth it, but I think it can be worth it in combination
with second extension.
Extension2: allow string literals that spans from an opening token till the
end of a line.
String s = "hello\n";
to be written as
String s =
"""hello
;
Tripple quotes in this case start a string literal which ends at an end of
line.
Having these two extensions, we can rewrite our example as:
String j =
"public static void " + name + """(String... args) {
""" System.out.println("Hello,\\t" + String.join(args));
"""}
;
Other examples:
String sql =
"""SELECT name
"""FROM user
"""WHERE id = ? and role = 'ADMIN'
;
String json =
"""{
""" "login": "john",
""" "id": 123.
"""}
;
String html =
"""<div class="active">
""" <span class="title">Hello, World</span>
"""</div>
;
With this style we can't just copy and past snippets of foreign code into a
string literal, but
all we need is to prefix every line with tripple quotes.
This style is analogues to source code comments handling by programmers,
so, I think, it's familiar enough.
// TODO: rewrite this method
// using new guava API
Automatic prefixing of comments is already present in every IDE and is
simple enough to implement by hand, like
| sed 's/^/"""/g'
Rawness can be added to such string literals independently in orthogonal
way:
String regex = \"a(bc)+\s+(de|kg)?"\;
String j =
\"public static void "\ + name + \"""(String... args) {
\""" System.out.println("Hello,\t" + String.join(args));
\"""}
;
The problem I see is interoperability between simple string literals and
"line sting literals": we can't easily align them vertically.
But may be this problem is more easily solvable than magical incidental
whitespace handling.
--
Victor Nazarov
More information about the amber-spec-comments
mailing list