Saturday, November 02, 2019

Java 13: Enhancements to Switch Expressions

You may remember from my previous post that, in Java 12, the traditional switch statement was enhanced so that it could be used as an expression. In Java 13, there has been a further change to this feature. The break statement can no longer return a value. Instead, you have to use the new yield statement, as shown below:

final int result = switch (input) {
    case 0, 1 -> 1;
    case 2 -> 4;
    case 3 -> {
      System.out.println("Calculating: " + input);
      final int output = compute(input);
      System.out.println("Result: " + output);
      yield output;
    }
    default -> throw new IllegalArgumentException("Invalid input " + input);
};

Note that this is still a preview language feature, which means that it must be explicitly enabled in the Java compiler and runtime using the --enable-preview flag.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.