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?
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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With