使用类似Lambda的语法切换为Java中的表达式
從Java 14開始, switch表達(dá)式具有額外的Lambda式 ( case ... -> labels )語法,它不僅可以用作語句,還可以用作計(jì)算為單個(gè)值的表達(dá)式。
使用新的類似Lambda的語法,如果標(biāo)簽匹配,則僅執(zhí)行箭頭右側(cè)的表達(dá)式或語句;否則,僅執(zhí)行箭頭右側(cè)的表達(dá)式或語句。 沒有跌倒:
var result = switch (str) { case "A" -> 1 ; case "B" -> 2 ; case "C" -> 3 ; case "D" -> 4 ; default -> throw new IllegalStateException( "Unexpected value: " + str); };上面是switch作為返回單個(gè)整數(shù)值的表達(dá)式的示例。 可以在switch中將相同的語法用作語句:
int result; switch (str) { case "A" -> result = 1 ; case "B" -> result = 2 ; case "C" -> { result = 3 ; System.out.println( "3!" ); } default -> { System.err.println( "Unexpected value: " + str); result = - 1 ; } }yield
在case需要塊的case , yield可用于從中返回值:
var result = switch (str) { case "A" -> 1 ; case "B" -> 2 ; case "C" -> { System.out.println( "3!" ); yield 3 ; // return } default -> throw new IllegalStateException( "Unexpected value: " + str); };每種
也可以在每種case使用以逗號(hào)分隔的多個(gè)常量,進(jìn)一步簡(jiǎn)化了switch的使用:
var result = switch (str) { case "A" -> 1 ; case "B" -> 2 ; case "C" -> 3 ; case "D" , "E" , "F" -> 4 ; default -> 5 ; };最后的例子
為了演示新的switch語法,我創(chuàng)建了這個(gè)微型計(jì)算器:
double calculate(String 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)); }; }源代碼
可以在Github上找到本文的源代碼: https : //github.com/kolorobot/java9-and-beyond
參考文獻(xiàn)
- https://openjdk.java.net/jeps/361
翻譯自: https://www.javacodegeeks.com/2020/05/switch-as-an-expression-in-java-with-lambda-like-syntax.html
總結(jié)
以上是生活随笔為你收集整理的使用类似Lambda的语法切换为Java中的表达式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星Galaxy S24 Ultra搭载
- 下一篇: 超音速亚原子Enterprise Jav