java switch 表达式_Switch表达式

Switch 表达式

JDK 12

目前实现的特性:Switch Expressions (Preview)

Raw String Literals (Preview)

One AArch64 Port, Not Two

Default CDS Archives

非常遗憾模式匹配还是没赶上,而JEP 325: Switch Expressions (Preview)作为JEP 305: Pattern Matching的先导特性已经可以试用了.

$ /javac --version

javac 12-ea

Expression

顾名思义,现在的switch是表达式,他是有值的:

public class Test {

enum Alpha{

A,B,C,D,E

}

static char fun(Alpha alpha){

var r = switch (alpha){

case A -> 'a';

case B -> 'b';

case C -> 'c';

case D -> 'd';

};

return r;

}

public static void main(String[] args){

System.out.print(fun(Alpha.A));

}

}

Switch Expression目前还是预览特性,编译需要加上--enable-preview

$ javac --release 12 --enable-preview -Xlint:preview Test.java

Test.java:7: warning: [preview] switch expressions are a preview feature and may be removed in a future release.

var r = switch (alpha){

^

Test.java:8: warning: [preview] switch rules are a preview feature and may be removed in a future release.

case A -> 'a';

^

Test.java:9: warning: [preview] switch rules are a preview feature and may be removed in a future release.

case B -> 'b';

^

Test.java:10: warning: [preview] switch rules are a preview feature and may be removed in a future release.

case C -> 'c';

^

Test.java:11: warning: [preview] switch rules are a preview feature and may be removed in a future release.

case D -> 'd';

^

Test.java:7: error: the switch expression does not cover all possible input values

var r = switch (alpha){

^

1 error

5 warnings

可以看到,编译器目前可以检查是否写完整所有的"模式",虽然他还还不能告诉你哪里漏写了.

$ java --enable-preview Test

a%

你还可以换一种方式,在switch语句中用break返回switch表达式的值:

var r = switch (alpha){

case A :

break 'a';

case B :

break 'b';

case C :

break 'c';

case D :

break 'd';

case E :

break 'e';

};

编译:

javac --release 12 --enable-preview -Xlint:preview Test.java

Test.java:7: warning: [preview] switch expressions are a preview feature and may be removed in a future release.

var r = switch (alpha){

^

1 warning

这次警告要少一些,很神奇.

不过我还是认为 switch 代码块赋值给变量,后面还是要加上分号很奇怪.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值