JEP 430 String Templates, some weird scenarios feedback
Brian Goetz
brian.goetz at oracle.com
Thu Jun 15 22:47:07 UTC 2023
On 6/15/2023 6:01 PM, Anatoly Kupriyanov wrote:
> I understand why it works like that but it still causes some confusion
> to me, at least it should be somehow documented:
>
> var val = 1; var template = RAW."val = \{val}"; assert
> template.interpolate().equals("val = 1");
> val = 2; assert template.interpolate().equals("val = 1");//weird
Yes, a template closes over values, not variables. We could adopt the
same constraint as we do with lambdas / inner classes -- require that
any referenced variables be effectively final -- but this would likely
be quite restrictive given the typical use cases for string templates.
>
> Another thing, I could not figure out a reasonable conditional
> template syntax and nesting. This looks kind of ugly and hard to read
>
> String msg(String name, String val)
> { return STR."Today is a nice day. \{name == null ? "" : STR."Hello
> \{name}! "}You have \{val}thing.";
> }
> assert msg(null, "this").equals("Today is a nice day. You have this
> thing."); assert msg("World", "that").equals("Today is a nice day.
> Hello World! You have that thing.");
>
> This thing would be especially important e.g. for a JSON tree templating.
>
Whenever you have an expression that is so complicated or deeply nested
that it is hard to read, the standard trick is to break it up. This is
not unique to string templates.
var n = (name == null) ? "" : STR."Hello \{name}! ";
return STR."Today is a nice day. \{n} You have \{val} thing.";
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230615/2ed7e0b8/attachment-0001.htm>
More information about the amber-dev
mailing list