加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala编码标准:同一行上的花括号

发布时间:2020-12-16 19:15:36 所属栏目:安全 来源:网络整理
导读:scala coding standards表示 Technically,Scala’s parser does support GNU-style notation with opening braces on the line following the declaration. However,the parser is not terribly predictable when dealing with this style due to the way in
scala coding standards表示

Technically,Scala’s parser does support GNU-style notation with opening braces on the line following the declaration. However,the parser is not terribly predictable when dealing with this style due to the way in which semi-colon inference is implemented. Many headaches will be saved by simply following the curly brace convention demonstrated above.

我看了,我找不到任何真实的例子.任何人都可以用exmaple来解释这背后的原因吗?有没有人在新线上使用花括号时遇到问题?

解决方法

考虑这个表达式:

someElement
{
   // Some code
}

这怎么解释?它是一个表达式(例如一个值,或一个没有参数的函数调用)后跟一个括在括号中的块语句?或者它是一个函数调用,括号括起一个参数?

如果Scala没有分号推断 – 也就是说,如果Scala要求分号以与Java相同的方式表示语句的结尾 – 那么这两者可以很容易地区分,因为前者需要在分号结尾处使用分号第一行.但是,Scala解析器必须推断分号的位置才能理解代码,有时它会出错. (根据上下文,这两种解释都是有效的,并且Scala解析器并不总是能够自行解决歧义.)

例如,假设someElement是一个带有by name参数的函数.如果你试图在Scala REPL中调用它,打算将参数(在大括号内)放在另一行上,你会发现单独输入someElement会导致错误:

> scala
Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM,Java 1.8.0_161).
Type in expressions for evaluation. Or try :help.

scala> def someElement(x: => Int): Int = {
     |   // Do something...
     |   x
     | }
someElement: (x: => Int)Int

scala> someElement
<console>:13: error: missing argument list for method someElement
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `someElement _` or `someElement(_)` instead of `someElement`.
       someElement
       ^

也就是说,你甚至没有进入大括号.但是,如果您输入以下内容,那么您就可以了:

scala> someElement {
     |   10
     | }
res0: Int = 10

但是如果someElement是一个值呢?现在我们在REPL中看到这个:

scala> val someElement = 5
someElement: Int = 5

scala> someElement
res1: Int = 5

scala> {
     |   5
     | }
res2: Int = 5

现在,REPL在不同的行上接受相同的代码,作为两个不同的表达式.

让我们变得非常暧昧.假设someElement是一个值,但现在它是一个带有单个参数的函数的引用.让我们来看看可能的解释:

scala> def square(a: Int) = a * a
square: (a: Int)Int

scala> val someElement = square _
someElement: Int => Int = $$Lambda$1034/1609754699@74abbb

scala> someElement
res3: Int => Int = $$Lambda$1034/1609754699@74abbb

scala> {
     |   5
     | }
res4: Int = 5

也就是说,它被视为两个单独的语句:一个值后跟一个块语句.然而:

scala> someElement {
     |   5
     | }
res5: Int = 25

被视为对square的调用,参数为5.

Scala编译器比REPL更聪明,因为它可以同时看到所有代码,并将通过查看哪些替代方案最有意义来尝试解决歧义,但其解释可能并不总是与您的解释相匹配.

因此,正如您所看到的,将开括号放在同一行 – 如果两个表达式是链接的 – 使关系显式化并消除歧义.或者,如果您希望将表达式明确地解析为单独的语句,请在第一行之后添加分号.

(恕我直言,分号推断是斯卡拉的阿喀琉斯之踵.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读