我正在翻阅这本精彩的书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.加宽 that.width
^
为什么这种语法不可接受?
第2行使用方法widen
作为运算符,而不是像 Java 那样将其用作方法:
val this1 = this.widen(that.width)
发生错误的原因是您遗漏了括号,而只有在使用运算符表示法中的方法时才能执行此操作。你can't例如这样做:
"a".+ "b" // error: ';' expected but string literal found.
相反你应该写
"a".+ ("b")
实际上你可以用整数来做到这一点,但这超出了这个问题的范围。
阅读更多:
- 你的书的第 5 章第 3 节是关于运算符符号的,至少在第一版,第 5 版中是这样的
- Scala 之旅:运算符
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)