Home > Software design >  Compilation error in certain pattern of java's switch-yield syntax
Compilation error in certain pattern of java's switch-yield syntax

Time:11-28

An unknown syntax error occurs due to the Logical not sign while writing Java's switch-yield statement. After the yield as below '!' will cause a compilation error.

final var error = switch(args[0]) {
    case "A" -> {
        yield !true || true;
    }
    default -> false;
};

The compile error message printed out is:

error: not a statement
                yield !true || true;
                ^

As follows '!' After writing the code, it compiles successfully.

final var success = switch(args[0]) {
    case "A" -> {
        yield true || !true;
    }
    default -> false;
};

CodePudding user response:

It's a JDK bug.

See [JDK-8268670] yield statements doesn't allow ~ or ! unary operators in expression - Java Bug System

It seems to be resolved in version 17.

  • Related