Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 294
PrimosK Avatar asked Jan 30 '12 14:01

PrimosK


2 Answers

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.

like image 188
Tomasz Nurkiewicz Avatar answered Nov 04 '22 09:11

Tomasz Nurkiewicz


"1"+1 invokes java.lang.String's operator+, 1+"1" invokes an operator+ defined by the scala runtime (can't find it right now), so it returns a scala string.

like image 29
tstenner Avatar answered Nov 04 '22 09:11

tstenner