Scala 的中缀符号与对象 +,为什么不可能? [英] Scala's infix notation with object +, why not possible?

查看:41
本文介绍了Scala 的中缀符号与对象 +,为什么不可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样命名对象,但不能调用m:

I can name objects like this, but can't call m:

object + {
  def m (s: String) = println(s)
}

无法调用+.m("hi"):

<console>:1: error: illegal start of simple expression
       +.m("hi")

也不能调用 + m "hi"(首选 DSL 使用).

Also can't call + m "hi" (preferred for DSL-usage).

但是使用 object ++ 它可以正常工作!它们是否与(不存在的)unary_+ 方法冲突?有没有可能避免这种情况?

But with object ++ it works fine! Do they conflict with (not existent) unary_+ methods? Is it possible to avoid this?

推荐答案

事实上,一元运算符是不可能的.如果您无论如何都想调用它,您可以使用编译器为 JVM 生成的名称(以美元开头):

Indeed it is not possible with unary operators. If you want to call it anyways, you could resort to using the name generated by the compiler for the JVM (which starts with a dollar):

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 的中缀符号与对象 +,为什么不可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆