Comments Inside Text Block in Java 17 - Is that possible?

Viewed 688

A simple question. Is it possible to have comments in Text Blocks in Java 17?

Since Java 15 Text Blocks are an option:

"""
   Hello Hello                    //how to create a comment here? - this was wanted by customer XXX
This dog has a big nose        // This line came with version 1.0.2
This cat needs to eat
"""

Is it possible to have comments inside a text block? I would like to tag some lines that came with new customers etc. Is this possible, will this be possible?

3 Answers

The Java Language Specification states that:

The lexical grammar implies that comments do not occur within character literals, string literals, or text blocks

(emphasis mine)

So nope, you can't do that.

As of JEP 378, it is not possible to add a comment in a text block.

However, you can use a few tricks:

For example, you can replace everything inside of /*... */:

"""
abc /* this is a comment*/
def //another comment
""".replace("/\\*.*\*/","").replace("//.*$","");

Another possibility would be to use multiple text blocks:

"""
... 
"""
+ //comment
"""
... 
"""

However, as Federico klez Culloca mentioned in the comments, these are just workarounds. It is likely better to include a comment before the text block explaining what it does in general instead of writing comments in the text blocks.

I don't know specially for Java but I would think that no it isn't possible to do this as some people would want to have text with // in the strings without escaping.

Related