Search code examples
javastringjava-15

How can i add variables inside Java 15 text block feature?


Just came across a new feature in Java 15 i.e. "TEXT BLOCKS". I can assume that a variable can be added inside a text block by concatenating with a "+" operator as below:

String html = """
          <html>
              <body>
                  <p>Hello, """+strA+"""</p>
              </body>
          </html>
          """;

But are they providing any way so that we can add variables the way which is becoming popular among many other languages as below:

String html = """
          <html>
              <body>
                  <p>Hello, ${strA}</p>
              </body>
          </html>
          """;

This question might sound silly but it may be useful in certain scenario.


Solution

  • From the spec for text blocks:

    Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP.

    "String interpolation" meaning

    evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values

    from Wikipedia


    As stated above, maybe we'll get it in the future. Though it is difficult to say how they could possibly implement that without breaking backwards compatibility -- what happens if my string contains ${}, for example? The Java language designers rarely add anything that is likely to break backwards compatibility.

    It seems to me that they would be better off either supporting it immediately, or never.

    Maybe it would be possible with a new kind of text block. Rather than the delimiter being """, they could use ''' to denote a parameterized text block, for example.