为什么在括号上使用花括号? [英] Why use curly braces over parentheses?

查看:168
本文介绍了为什么在括号上使用花括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多Scala示例中,我发现人们很容易在很奇怪的地方使用花括号,而使用括号可以轻松写出相同的语句.

In a lot of Scala examples I see people use curly braces in places I find outright strange, when the same statement could easily be written using parentheses.

示例:

lst foreach (x => println(s"the value returned is: $x")) // parens
lst foreach {x => println(s"you get the idea, $x")} // braces

我知道您可以使用括号代替括号,这仅仅是因为它允许您在多行上写一条语句:

I understand that you can use braces as an alternative to parentheses, simply because it allows you to write a statement on multiple lines:

val res = for {
  x <- coll1
  y <- coll2
} yield (x, y) 

  • 因此,当将它写在一行上时,是否有固有的理由要使用一个而不是另一个?
  • 最后的结果应该是一样的,还是我错过了什么?
  • 还是仅仅是风格和/或个人品味的问题?
  • 推荐答案

    通常,在很多情况下,您希望使用花括号(例如,用于理解的多行表达式),但是让我们来专门讨论

    In general, there are many cases when you would prefer curly braces (e.g. multiline expressions, for comprehensions), but let's talk specifically about

    当它写在一行上时,是否有固有的理由要在另一行上使用它

    在第二种情况下,它不仅是大括号,而且不是括号,而是带有省略括号的大括号. Scala有时允许您省略括号,而后面的语法用于访问部分函数(即模式匹配)中的精妙之处,因此

    In a second case it's not just curly braces, instead of parentheses, it's curly braces with ommited parentheses. Scala allows you to ommit parenthesis sometimes, and the later syntax is used to access to the niceties you got in partial functions (namely, pattern matching), so

    lst foreach {x => println(s"you get the idea, $x")}
    

    实际上是

    lst foreach({x => println(s"you get the idea, $x")})
    

    正如我说的,它可以从模式匹配POV中使用:

    which, as I said, can be useful from pattern matching POV:

    val map = Map("foo" -> "bar")
    map foreach { case (k, v) => println(s"key: $k, value: $v") }
    // which is not possible with the usual parenthesis
    

    这篇关于为什么在括号上使用花括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆