我可以这样命名对象,但是不能调用m
:
object + {
def m (s: String) = println(s)
}
无法调用
+.m("hi")
:<console>:1: error: illegal start of simple expression
+.m("hi")
也不能调用
+ m "hi"
(DSL使用首选)。但是使用
object ++
可以正常工作!它们是否与unary_+
方法(不存在)冲突?有可能避免这种情况吗?
最佳答案
实际上,一元运算符是不可能的。如果您仍然要调用它,则可以使用由编译器为JVM生成的名称(以美元开头):
scala> object + {
| def m( s: String ) = println(s)
| }
defined module $plus
scala> +.m("hello")
<console>:1: error: illegal start of simple expression
+.m("hello")
^
scala> $plus.m("hello")
hello
关于Scala的带对象+的中缀表示法,为什么不可能呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13367122/