Java 中 return 用 Scala 表达

6 篇文章 0 订阅
Scala 中没有 break(2.8 中将会支持) 和 continue,的确是件纠结的事情啊~
更纠结的是,return 似乎也不能直接 work
比如 Java 里头可以这样写(虽然这样写并不好):
for(int i = 0; i < 10; i++){
            System.out.println("i = " + i);
            if(i == 1){
                System.out.println("return at i = 1");
                return;
            }else if( i == 2){
                System.out.println("return i = 2");
                return ;
            }
       }


但是 Scala 里头怎么办列,或许换种思考的方式会更好:
(0 until 10).find{ i => 
  println("i = " + i)
  i match {
  case 1 => println("return at i = 1"); true
  case 2 => println("return at i = 2"); true
  case _ => false
}}


对于 break 和 continue,
引用
These keywords are not included in Scala 2.7, and must be implemented in a different way. For break, the simplest thing to do is to divide your code into smaller methods and use the return to exit early. For continue, a simple approach is to place the skipped-over parts of a loop into an if.

Scala 2.8 will include break, but not continue.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值