How to unimport String “+” operator in Scala?

折月煮酒 提交于 2019-11-27 06:41:20

问题


I'm writing a DSL where the "+" operator is strictly numeric, like some other popular languages. It's close, but the String "+" operator is messing up my implicit conversions. What's the syntax for unimporting an operator of the String class?

Just to be clearer, instead of this:

scala> var x = "2" + 3;
x: java.lang.String = 23

I'd like to get x: Int = 5

I imagine I just need 2 things to make that happen:

  • Remove (unimport within my scope) the definition of "+" from Strings
  • Define an implicit conversion of String to Int

I'm stuck on the first step.

Thanks


回答1:


According to section 12.3.1 of the Scala spec, the + method for String has special treatment by the compiler. I don't know for sure, but I think this means you can't "unimport" it, which is a shame because it really breaks the type system (much like the related toString method).

Could you use a different name for the operator in your DSL, eg, ++ or &?




回答2:


The + method for a string is a method on of the String class (and therefore on each string object), and as such it cannot be unimported.




回答3:


You can't unimport it, but you could use +: and define it on the int class. What would be best is if you write it like this: "2".toInt + 3.



来源:https://stackoverflow.com/questions/2664274/how-to-unimport-string-operator-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!