Scala中()与{}的关系

Scala中()与{}的关系

在Scala中有些时候()和{}是可以相互替换的,但是如果不弄清楚到底什么时候该用(),什么时候该用{},什么时候二者可以相互替换,那么在写代码的时候难免为出错,并且自己还发现不了。这里有以下几个使用原则:
 curly braces form a block of code, which evaluates to the last line of code (all languages do this);
 a function if desired can be generated with the block of code (follows rule 1);
 curly braces can be omitted for one-line code except for a case clause (Scala choice);
 parentheses can be omitted in function call with a single parameter (Scala choice);
 almost never omit both。
即:
 大括号{}用于代码块,计算结果是代码最后一行;
 大括号{}用于拥有代码块的函数;
 大括号{}在只有一行代码时可以省略,除了case语句(Scala适用);
 小括号()在函数只有一个参数时可以省略(Scala适用);
 几乎没有二者都省略的情况。
下面有几个例子,仅供参考(待更新):
[plain]  view plain  copy
  1. val tupleList = List[(String, String)]()  
  2. // doesn't compile, violates case clause requirement  
  3. val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )   
  4. // block of code as a partial function and parentheses omission,  
  5. // i.e. tupleList.takeWhile({ case (s1, s2) => s1 == s2 })  
  6. val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }  
  7.   
  8. // curly braces omission, i.e. List(1, 2, 3).reduceLeft({_+_})  
  9. List(1, 2, 3).reduceLeft(_+_)  
  10. // parentheses omission, i.e. List(1, 2, 3).reduceLeft({_+_})  
  11. List(1, 2, 3).reduceLeft{_+_}  
  12. // not both though it compiles, because meaning totally changes due to precedence  
  13. List(1, 2, 3).reduceLeft _+_ // res1: String => String = <function1>  
  14.   
  15. // curly braces omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})  
  16. List(1, 2, 3).foldLeft(0)(_ + _)  
  17. // parentheses omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})  
  18. List(1, 2, 3).foldLeft(0){_ + _}  
  19. // block of code and parentheses omission  
  20. List(1, 2, 3).foldLeft {0} {_ + _}  
  21. // not both though it compiles, because meaning totally changes due to precedence  
  22. List(1, 2, 3).foldLeft(0) _ + _  
  23. // error: ';' expected but integer literal found.  
  24. List(1, 2, 3).foldLeft 0 (_ + _)  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值