问题描述
我正在阅读精彩的书在 Scala 中编程遇到一段对我来说毫无意义的代码:
I was going through the wonderful book Programming in Scala when I came across a piece of code that just doesn't make sense to me:
def above(that: Element): Element = {
val this1 = this widen that.width
val that1 = that widen this.width
elem(this1.contents ++ that1.contents)
}
注意第 2 行和第 3 行:
Note line 2 and 3:
val this1 = this widen that.width
看来我应该可以用:
val this1 = this.widen that.width
但是,当我尝试编译此更改时,会出现以下错误:
However, when I try to compile this change, it gives the following error:
错误:';'预期但'.'成立.
val this1 = this.widen that.width^
为什么这种语法不可接受?
Why is this syntax unacceptable?
推荐答案
第 2 行将方法 widen
用作操作符,而不是将其用作 Java 方式中的方法:
Line 2 uses the method widen
as an operator, instead of using it as a method in the Java way:
val this1 = this.widen(that.width)
发生错误是因为您省略了括号,只有在使用运算符表示法的方法时才能这样做.您不能这样做,例如:
The error occurs because you've left out the parentheses, which you can only do when you use a method in operator notation. You can't do this for example:
"a".+ "b" // error: ';' expected but string literal found.
你应该写
"a".+ ("b")
实际上你可以用整数来做到这一点,但这超出了这个问题的范围.
Actually you can do this with integers, but that's beyond the scope of this question.
阅读更多:
- 您的书的第 5 章第 3 节是关于运算符表示法的,至少在第一版第 5 版中是这样的
- Scala 之旅:运算符
这篇关于Scala 点语法(或缺少语法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!