2009-08-05 71 views
9

我经历的精彩的书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 

然而,当我尝试编译这种变化,它提供了以下错误:

error: ';' expected but '.' found.
val this1 = this.widen that.width ^

这是为什么语法不能接受?

+1

可能的重复:http://stackoverflow.com/questions/1181533/what-are-the-precise-rules-for-when-you-can-omit-parenthesis-dots-braces-fu和http:// stackoverflow.com/questions/1006967/scala-which-characters-can-i-omit – 2009-08-05 17:08:10

回答

17

行2使用方法widen作为一个经营者,而不是使用它作为Java的方式方法:

​​

,因为你忽略了括号,你只能做出现的错误当您在运算符表示法中使用方法时。您不能例如这样做:

"a".+ "b" // error: ';' expected but string literal found. 

相反,你应该写

"a".+ ("b") 

其实你可以用整数做到这一点,但这已经超出了这个问题的范围。

了解更多:

3

我还没有尝试过,但也许这个作品:val this1 = this.widen(that.width)

widen可能是服用一个参数(加上this参考)的方法,这种方法可以像运营商可以作为你的第一个示例代码。