【问题标题】:Scala dot syntax (or lack thereof)Scala点语法(或缺少)
【发布时间】:2009-08-05 13:29:18
【问题描述】:

我正在阅读这本精彩的书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 ^

为什么这种语法不可接受?

【问题讨论】:

标签: java syntax scala


【解决方案1】:

第 2 行使用方法 widen 作为运算符,而不是使用 Java 方式作为方法:

val this1 = this.widen(that.width)

发生错误是因为您遗漏了括号,只有在使用运算符表示法的方法时才能这样做。例如,您不能这样做:

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

你应该写

"a".+ ("b")

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

阅读更多:

【讨论】:

    【解决方案2】:

    我没有尝试过,但也许这可行:val this1 = this.widen(that.width)

    widen 可能是一个带有一个参数的方法(加上this 引用),这些方法可以像您的第一个示例代码中的运算符一样使用。

    【讨论】:

      【解决方案3】:

      当您使用点时,您使用点样式进行方法调用。如果不这样做,则使用运算符样式。您不能将两种语法混合用于同一个方法调用,尽管您可以将两种语法混合用于不同的调用——例如 that.width 用作加宽运算符样式调用中的参数。

      请参考Which characters can I omit in Scala?What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多