非法文本块打开定界符序列,缺少行终止符

illegal text block open delimiter sequence, missing line terminator

Java13来了,于是开始研究它的新特性,其中之一就是text blocks.

我写了一个简单的程序

public final class Example {
    public static void main(String[] args) {
        final String greeting = """Hello
        It's me, Andrew!""";
        System.out.println(greeting);
    }
}

我期待看到

Hello
It's me, Andrew!

我得到的是编译错误

illegal text block open delimiter sequence, missing line terminator

文本块的上下文必须从新行开始。

public final class Example {
    public static void main(String[] args) {
        final String greeting = """
            Hello
            It's me, Andrew!""";
        System.out.println(greeting);
    }
}

打印

Hello
It's me, Andrew!

摘自JEP 355: Text Blocks (Preview)

A text block consists of zero or more content characters, enclosed by opening and closing delimiters.

The opening delimiter is a sequence of three double quote characters (""") followed by zero or more white spaces followed by a line terminator. The content begins at the first character after the line terminator of the opening delimiter.

不过,您不一定非要在内容末尾放置行终止符。

The closing delimiter is a sequence of three double quote characters. The content ends at the last character before the first double quote of the closing delimiter.

final String greeting = """
    Hello
    It's me, Andrew!
    """;

表示

Hello
It's me, Andrew!
<an empty line here>

我觉得非常不清楚,所以我不得不与社区分享。

郑重声明,a rationale for the decision not to allow content immediately after """ is given here

The reason for this is that text blocks are primarily designed to support multi-line strings, and requiring the initial line terminator simplifies the indentation handling rules