illegal text block open delimiter sequence, missing line terminator
Asked Answered
L

2

7

Java 13 is coming, so I started studying its new features, one of which is text blocks.

I wrote a simple program

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

I was expecting to see

Hello
It's me, Andrew!

What I got is a compilation error saying

illegal text block open delimiter sequence, missing line terminator

Lesslie answered 9/9, 2019 at 11:35 Comment(0)
L
15

The context of your text block must start from a new line.

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

prints

Hello
It's me, Andrew!

An excerpt from 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.

You don't necessarily have to put a line terminator at the end of your content, though.

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!
    """;

would mean

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

I find it extremely unclear, so I had to share this with the community.

Lesslie answered 9/9, 2019 at 11:35 Comment(0)
F
2

For the record, 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

Fess answered 22/4, 2021 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.