views:

186

answers:

2

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

+6  A: 

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 &?

Kristian Domagala
The fact that the `+` method get special treatment by the compiler has nothing to do with whether it can be imported or unimported. The language is supposed to be very orthagonal, and treat all class methods semantically the same, regardless of whether they're syntheized by the compiler or provided by the runtime library.
Ken Bloom
I would agree with what you are saying if `+` were indeed explicitly specified on the `String` class, but the specification only alludes to this, and IMO could be interpreted as saying that there is an implicit conversion (that is baked into the compiler and hence can't be "unimported") to some type (eg, `StringAdd`), which allows clients to treat `String` as if it were defined with a `+` method. I'm happy to be proven wrong here, but even through runtime reflection on `String` (and `RichString`), I can't find a `+` (ie `$plus`) method.
Kristian Domagala
Thanks, sounds like another case of "compiler magic" which actually breaks orthogonality and has unexpected interactions with other language features and libraries.
Alex R
Yes, I'm not sure why it couldn't be implemented in the same way as `Predef.any2stringadd`, eg `Predef.string2stringadd:String => StringAdd`.
Kristian Domagala
+2  A: 

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.

Ken Bloom