为什么以下不起作用? Scala 是否不允许在表达式开头对作用域方法进行中缀调用?
class Foo {
def foo(x: String) = 1
}
class Bar extends Foo {
val bar1 = foo("42") // compiles
val bar2 = this foo "42" // compiles
val bar3 = foo "42" // does not compile
}
最佳答案
正如 @sjrd 所说,foo "42"
不是中缀调用。在中缀调用中,运算符必须中缀在两个对象之间。即具有以下形式:
<object1> <operator> <object2>
foo "42"
是前缀调用。即具有以下形式:
<operator> <object>
在 Scala 中,根据 SLS,前缀调用仅限于 +
、-
、!
或 ~
:
A prefix operation op;e consists of a prefix operator op, which must be one of the identifiers ‘+’, ‘-’, ‘!’ or ‘~’. The expression op;e is equivalent to the postfix method application e.unary_op.
这就是为什么 this foo "42"
有效,但 foo "42"
无效。
关于scala - <this> 上的中缀调用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32306281/