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)); }; }
分类:
Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2022-04-09 Spring: 配置声明式事务