Scala';带对象的s中缀表示法+;,为什么不可能?
我可以这样命名对象,但不能调用Scala';带对象的s中缀表示法+;,为什么不可能?,scala,Scala,我可以这样命名对象,但不能调用m: object + { def m (s: String) = println(s) } 无法调用+.m(“hi”): :1:错误:简单表达式的启动非法 +.m(“你好”) 也不能调用+m“hi”(DSL使用时首选) 但是使用object++它工作得很好!它们是否与(不存在的)一元方法冲突?有可能避免这种情况吗?事实上,使用一元运算符是不可能的。如果您想以任何方式调用它,可以使用编译器为JVM生成的名称(以美元开头): scala>object+{ |d
m
:
object + {
def m (s: String) = println(s)
}
无法调用+.m(“hi”)
:
:1:错误:简单表达式的启动非法
+.m(“你好”)
也不能调用+m“hi”
(DSL使用时首选)
但是使用
object++
它工作得很好!它们是否与(不存在的)一元方法冲突?有可能避免这种情况吗?事实上,使用一元运算符是不可能的。如果您想以任何方式调用它,可以使用编译器为JVM生成的名称(以美元开头):
scala>object+{
|def m(s:String)=println(s)
| }
已定义模块$plus
scala>+.m(“你好”)
:1:错误:简单表达式的开始非法
+.m(“你好”)
^
scala>$plus.m(“你好”)
你好
我认为问题在于,为了处理一元运算符而不产生歧义,scala依赖于一种特殊情况:仅
、+
、-
和~
被视为一元运算符。因此,在+.m(“hi”)
中,scala将+
视为一元运算符,无法理解整个表达式。另一个使用包的代码:
object Operator extends App {
// http://stackoverflow.com/questions/13367122/scalas-infix-notation-with-object-why-not-possible
pkg1.Sample.f
pkg2.Sample.f
}
package pkg1 {
object + {
def m (s: String) = println(s)
}
object Sample {
def f = {
// +.m("hi") => compile error: illegal start of simple expression
// + m "hi" => compile error: expected but string literal found.
$plus.m("hi pkg1")
$plus m "hi pkg1"
}
}
}
package pkg2 {
object + {
def m (s: String) = println(s)
}
object Sample {
def f = {
pkg2.+.m("hi pkg2")
pkg2.+ m "hi pkg2"
pkg2.$plus.m("hi pkg2")
pkg2.$plus m "hi pkg2"
}
}
}
java版本“1.7.0_09”
Scala code runner 2.9.2版不幸的是,我只能猜测为什么不能使用+,但可以使用
$plus.m(“hi”)
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
object Operator extends App {
// http://stackoverflow.com/questions/13367122/scalas-infix-notation-with-object-why-not-possible
pkg1.Sample.f
pkg2.Sample.f
}
package pkg1 {
object + {
def m (s: String) = println(s)
}
object Sample {
def f = {
// +.m("hi") => compile error: illegal start of simple expression
// + m "hi" => compile error: expected but string literal found.
$plus.m("hi pkg1")
$plus m "hi pkg1"
}
}
}
package pkg2 {
object + {
def m (s: String) = println(s)
}
object Sample {
def f = {
pkg2.+.m("hi pkg2")
pkg2.+ m "hi pkg2"
pkg2.$plus.m("hi pkg2")
pkg2.$plus m "hi pkg2"
}
}
}