Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unimport String "+" operator in Scala?

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

like image 471
Alex R Avatar asked Apr 18 '10 22:04

Alex R


People also ask

How do you write a string in Scala?

Creating a Stringvar greeting = "Hello world!"; or var greeting:String = "Hello world!"; Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”.

What is string * in Scala?

Scala string is an immutable object that means the object cannot be modified. Each element of a string is associated with an index number. The first character is associated with the number 0, the second with the number 1, etc. Class java. lang.

How do you declare a string variable in Scala?

Syntax. var myVar = 10; val myVal = "Hello, Scala!"; Here, by default, myVar will be Int type and myVal will become String type variable.

How do you read characters in Scala?

Console. readChar , aliased in in current incarnations of Scala as Predef. getChar is the most direct way. scala> readChar res0: Char = !


2 Answers

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

like image 118
Kristian Domagala Avatar answered Sep 21 '22 15:09

Kristian Domagala


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.

like image 22
Ken Bloom Avatar answered Sep 21 '22 15:09

Ken Bloom