Java: switch lambda-like syntax

 

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));
        };
    }
复制代码

 

posted @   ascertain  阅读(73)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2022-04-09 Spring: 配置声明式事务
点击右上角即可分享
微信分享提示