RFE: StringTemplate interpolation with custom function

Rob Spoor openjdk at icemanx.nl
Thu Oct 26 19:47:00 UTC 2023


I've been reading up on string templates, and I think it's a very cool 
feature. However, writing a custom processor can be a lot of copy-paste 
work if you want STR but with some extra translation applied. For 
instance, if I'd want to have a URL encoding processor I would have to 
write everything from scratch.

I think it would be useful to overload interpolate (both static and 
non-static) with a custom Function<Object, String> as additional 
arguments. This would work like STR if that provided String::valueOf as 
function.

With this method, creating a URL encoding processor would be as simple 
as this:

     var urlEncode = template -> template.interpolate(o ->
             URLEncoder.encode(String.valueOf(o), UTF_8));

     var url = urlEncode."https://host/path/\{id}?param=\{value\}";


Likewise, a processor backed by Apache Commons Text's StringEscapeUtils 
would now be just as simple:

     var CSV = template -> template.interpolate(o ->
             StringEscapeUtils.ESCAPE_CSV.translate(String.valueOf(o));

     var csv = CSV."""
             Header1, Header2, Header3
             "\{value1}", "\{value2}", "\{value3}"
             """;


If the JVM allows it, the existing interpolate method can even delegate 
to the new overload providing String::valueOf.


More information about the core-libs-dev mailing list