当我遇到一段对我来说没有意义的代码时,我正在经历这本精彩的书
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:@H_301_5@
- val this1 = this widen that.width
看来我应该可以用以下代替:@H_301_5@
- val this1 = this.widen that.width
但是,当我尝试编译此更改时,会出现以下错误:@H_301_5@
error: ‘;’ expected but ‘.’ found.
val this1 = this.widen that.width
^@H_301_5@
为什么这种语法不可接受?@H_301_5@
解决方法
第2行使用扩展方法作为运算符,而不是以Java的方式将其用作方法:
- val this1 = this.widen(that.width)
发生错误是因为您已经省略了括号,您只能在运算符符号中使用方法时执行此操作.你不能这样做:@H_301_5@
- "a".+ "b" // error: ';' expected but string literal found.
相反,你应该写@H_301_5@
- "a".+ ("b")
实际上你可以用整数来做,但这超出了这个问题的范围.@H_301_5@
阅读更多:@H_301_5@
>您的书的第5章第3节是关于操作符的符号,至少在第一版第5版中
> A Tour of Scala: Operators@H_301_5@