Java: switch lambda-like syntax

发布时间 2023-04-09 17:43:16作者: ascertain

 

The switch expression has an additional lambda-like syntax and it can be used not only as a statement, but also as an expression that evaluates to a single value.

 

With the new lambda-like syntax, if a label is matched, then only the expression or statement to the right of the arrow is executed; there is no fall through

package com.example.prom;

import java.util.Scanner;

public class D {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();
        byte result = switch (next) {
            case "A" -> 1;
            case "B" -> 2;
            default -> throw new IllegalStateException("Unexpected value: " + next);
        };
        System.out.println("result = " + result);
    }
}

 

package com.example.prom;

import java.util.Scanner;

public class D {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();
        int result;

        switch (next) {
            case "A" -> result = 1;
            case "B" -> result = 2;
            case "C" -> {
                result = 3;
                System.out.println("3!");
            }
            default -> {
                System.err.println("Unexpected value: " + next);
                result = -1;
            }
        }
        System.out.println("result = " + result);
    }
}

 

yield In the situation when a block is needed in a case, yield can be used to return a value from it

package com.example.prom;

import java.util.Scanner;

public class D {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();

        var result = switch (next) {
            case "A" -> 1;
            case "B" -> 2;
            case "C", "D", "E" -> {
                System.out.println("3!");
                yield 3;  // return
            }
            default -> throw new IllegalStateException("Unexpected value: " + next);
        };
        System.out.println("result = " + result);
    }
}

 

    protected double calculator(char operator, double x, double y) {
        return switch (operator) {
            case '+' -> x + y;
            case '-' -> x - y;
            case '*' -> x * y;
            case '/' -> {
                if (y == 0)
                    throw new IllegalArgumentException("Can't divide by 0");
                yield x / y;
            }
            default -> throw new IllegalArgumentException("Unknown operator `%s`".formatted(operator));
        };
    }