[string-templates] Accidental use of StringTemplate instead of string

Tagir Valeev amaembo at gmail.com
Thu Oct 20 14:44:07 UTC 2022


As stated in JEP 430 text, the string template is a well-formed
expression of StringTemplate type. Also, toString() method of
StringTemplate prints a debug-friendly representation like
[fragments](values) which is not intended for actual use. I can
imagine that the following mistake may happen often, especially by
inexperienced developers, or developers with background in other

int x = 10, y = 20;
System.out.println("\{x} plus \{y} equals \{x + y}");

Output expected by programmer: 10 plus 20 equals 30
Actual output (successfully compilable): ["", " plus ", " equals ",
""](10, 20, 30)

As an IDE vendor, we can surely provide an inspection for some
well-known methods like PrintStream#println(Object) with a quick-fix
to add a STR. prefix. However, not everybody uses IDEs. Probably the
language itself could help here somehow? E.g., uses of StringTemplate
where the Object type is expected might trigger a warning. This is
similar to array toString(), and every static analyzer has an
inspection about this. Honestly, I don't know a good solution but I
feel that it's not a good idea to introduce a new error-prone
construct, which is compilable and runnable, could be mistakenly used
and doesn't make sense.

As we are here, is it planned to specify StringTemplate equals and
hashCode? It's naturally a tuple of (fragments, values) lists, so
equals and hashCode could be defined. Also, current draft [1] suggests
that this is a non-sealed interface. Is it really intended to allow
third-party implementations?

Sorry if these questions were already discussed, I might skip some
discussions. I would be happy to see the pointers to previous

With best regards,
Tagir Valeev

[1] http://cr.openjdk.java.net/~jlaskey/templates/docs/api/java.base/java/lang/template/StringTemplate.html

More information about the amber-spec-experts mailing list