String interpolation: Difference between revisions

Content deleted Content added
Reverted 1 edit by 184.98.41.238 (talk) to last revision by Skywatcher68
Java: Java 21 now has string templates
Tags: nowiki added Visual edit
Line 142:
=== Java ===
{{Main article|Java (programming language)}}
Java 21 does have interpolated strings thanks to JEP 430. In [[JShell|jshell]] you could use the constant STR of [https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/StringTemplate.html java.lang.StringTemplate] directly.<syntaxhighlight lang="java" line="1">
{{as of|2022}}, Java does not have interpolated strings, and instead uses format functions, notably the <code>MessageFormat</code> class (Java version 1.1 and above) and the static method <code>String.format</code> (Java version 5 and above). [https://openjdk.org/jeps/430 There is a proposal] to add string interpolation to the Java language. This proposal aims at doing safe string interpolation, making it easier to prevent injection attacks.
enum Stage{test,qa,prod}
record Deploy(UUID image, Stage stage){}
var deploy=new Deploy(UUID.randomUUID(), Stage.test)
STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..."
var deploy=new Deploy(UUID.randomUUID(), Stage.prod)
STR."Installing \{deploy.image()} on Stage \{deploy.stage()} ..."
 
</syntaxhighlight>https://openjdk.org/jeps/430<nowiki/>{{Main article|JavaScript}}
=== JavaScript ===
{{Main article|JavaScript}}
 
[[JavaScript]], as of the [[ECMAScript]] 2015 (ES6) standard, supports string interpolation using backticks <code>``</code>. This feature is called ''template literals''.<ref>{{Cite web|url=https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals|title = Template literals (Template strings) - JavaScript &#124; MDN}}</ref> Here is an example: