Scala returns different types for very similar expressions

If I evaluate the following expression in a Scala REPL:

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

return type: java.lang.String .

If I evaluate this similar expression:

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

return type: String .

Why is the difference?

+5
source share
2 answers

There is no difference, however this is not a mistake either. In this case:

"1" + 1

you are using the Java built-in function to concatenate something into a String. In the end, many people convert numbers to strings using the following "idiom":

String s = "" + 5;

It works in Scala, and the result with java.lang.Stringis the same as in Java.

On the other hand:

1 + "1"

a little harder. This is translated into:

1.+("1")

+() Int.+, Int.scala:

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

String Predef.scala:

type String        = java.lang.String

"". , .

+14

"1"+1 java.lang.String operator +, 1+"1" +, scala ( ), scala.

+2

All Articles