PrimosK PrimosK - 4 months ago 17
Scala Question

Scala returns different types for very similar expressions

If I evaluate the following expression in Scala REPL:

scala> "1" + 1
res0: java.lang.String = 11


the returned type is: java.lang.String.

If I evaluate this similar expression:

scala> 1 + "1"
res1: String = 11


the returned type is: String.

Why the difference?

Answer

There is no difference, however it is also not a bug. In this case:

"1" + 1

you are using built-in feature of Java to concatenate anything into a String. After all, many people convert numbers to strings using the following "idiom":

String s = "" + 5;

It works in Scala as well and results with java.lang.String - same as in Java.

On the other hand:

1 + "1"

is a bit more complex. This is translated into:

1.+("1")

and the +() method is taken from Int.+ method located in Int.scala:

final class Int extends AnyVal {
    //....
    def +(x: String): String = sys.error("stub")

The String in this context is defined in Predef.scala:

type String        = java.lang.String

which is the source of the type "difference". As you can see both strings are in fact the same type.