运维开发网

为什么Scala编译器拒绝没有前导空格的函数体?

运维开发网 https://www.qedev.com 2020-06-22 19:27 出处:网络 作者:运维开发网整理
我发现这很令人困惑. scala> val a = (x:Boolean)=>!x <console>:7: error: not found: value x val a = (x:Boolean)=>!x ^ scala> val a = (x:Boolean)=> !x a: Boolean => Boolean = <function1> 两
我发现这很令人困惑.

scala> val a = (x:Boolean)=>!x
<console>:7: error: not found: value x
       val a = (x:Boolean)=>!x
                ^

scala> val a = (x:Boolean)=> !x
a: Boolean => Boolean = <function1>

两者之间的唯一区别是空白.是因为词法分析员认为=>!一个操作符?

你没错,它无法正确解析第一个版本.以下是为第一个和第二个选项生成的树的差异:

scala> import scala.reflect.runtime.{universe => u}
import scala.reflect.runtime.{universe=>u}

scala> import scala.reflect.runtime.{currentMirror => m}
import scala.reflect.runtime.{currentMirror=>m}

scala> import scala.tools.reflect.ToolBox
import scala.tools.reflect.ToolBox

scala> val tb = m.mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = [email protected]

scala> val treeNotWorking = tb.parse("(x:Boolean)=>!x")
treeNotWorking: tb.u.Tree = (x: Boolean).$eq$greater$bang(x)

scala> val treeWorking = tb.parse("(x:Boolean) => !x")
treeWorking: tb.u.Tree = ((x: Boolean) => x.unary_$bang)

如你所见,它试图调用=>!在其他地方定义的布尔变量x上.例如,如果我们在范围中有x,我们会得到一个不同的错误:

scala> val x = true
x: Boolean = true

scala> val a = (x:Boolean)=>!x
<console>:17: error: value =>! is not a member of Boolean
       val a = (x:Boolean)=>!x
0

精彩评论

暂无评论...
验证码 换一张
取 消