Scala:两个下划线后跟冒号解析为一个标记

时间:2016-06-28 21:48:36

标签: scala playframework

我最近玩的是Play的JSON库,并注意到这不能编译:

val steps = Seq("a", "b", "c")
steps.foldLeft(__)((a, x) => a \ x)

经过一些修补和浏览源代码后,我找到了正确的表达方式:

steps.foldLeft(JsPath())((a, x) => a \ x)

甚至:

steps.foldLeft(__())((a, x) => a \ x)

......虽然第二个看起来很模糊。

后来我发现了一个更有效,更简洁的表达方式:

JsPath(steps.toList map KeyPathNode)

但我一直回到原来的表情并玩弄它。我发现这有效:

steps.foldLeft(JsPath: JsPath)((a, x) => a \ x)

不知何故,这不是:

steps.foldLeft(__: JsPath)((a, x) => a \ x)

我得到error: not found: value __。但是,这有效:

steps.foldLeft((__): JsPath)((a, x) => a \ x)

这也有效:

steps.foldLeft({__}: JsPath)((a, x) => a \ x)

还有:

steps.foldLeft(__.asInstanceOf[JsPath])((a, x) => a \ x)

为什么__: JsPath的表达式会失败?

...... Aaaaa就在我提交这个问题之前,我发现了另一个有效的表达方式:

steps.foldLeft(__ : JsPath)((a, x) => a \ x)

解析器似乎将__:解释为一个令牌。但为什么会这样呢?我认为下划线只是另一个有效的标识符字符。是否有一些负责的特殊情况解析规则?

1 个答案:

答案 0 :(得分:3)

Underscore在标识符方面很特别,因为它可以跟随运算符字符,包括::例如foo_+是一个标识符,其中foo+是两个令牌:foo +

  

First, an identifier can start with a letter which can be followed by an arbitrary sequence of letters and digits. This may be followed by underscore _ characters and another string composed of either letters and digits or of operator characters.

请注意,_$在此处的第一句中被视为大写字母。因此__:是合法标识符,但_:不是。