当我遇到一段对我来说没有意义的代码时,我正在浏览这本精彩的书 Programming in Scala :
def above(that: Element): Element = {
val this1 = this widen that.width
val that1 = that widen this.width
elem(this1.contents ++ that1.contents)
}
注意第2和第3行:
val this1 = this widen that.width
似乎我应该能够将其替换为:
val this1 = this.widen that.width
但是,当我尝试编译此更改时,会出现以下错误:
错误:';'预期,但'。'找到。
val this1 = this.widen that.width ^
为什么这种语法不可接受?
答案 0 :(得分:17)
第2行使用方法widen
作为运算符,而不是以Java方式将其用作方法:
val this1 = this.widen(that.width)
发生错误是因为您省略了括号,只有在运算符表示法中使用方法时才能执行此操作。您不能执行此操作,例如:
"a".+ "b" // error: ';' expected but string literal found.
相反,你应该写
"a".+ ("b")
实际上你可以用整数来做到这一点,但这超出了这个问题的范围。
了解更多:
答案 1 :(得分:3)
我没有尝试过,但也许这有效:val this1 = this.widen(that.width)
widen
可能是一个采用一个参数(加上this
引用)的方法,这些方法可以像第一个示例代码一样使用运算符。
答案 2 :(得分:2)
当您使用点时,您使用点样式进行方法调用。如果不这样做,则使用运算符样式。您不能将两种语法混合在同一个方法调用中,尽管您可以将两者混合用于不同的调用 - 例如在扩展的操作员样式调用中用作参数的那个。
请参阅Which characters can I omit in Scala?或What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.?。