I am having a little trouble understanding the rationale behind the following few pieces of scala code:
We all know that 1 + 1 = 2 in the REPL.
scala> 1 + 1
res0: Int = 2
If I type in "Abc" + "Def", I should get "AbcDef" in the REPL.
scala> "Abc" + "Def"
res6: java.lang.String = AbcDef
Now let's say I invoke the + method on String "Abc" and pass "Def" as a parameter:
scala> "Abc".+("Def")
res7: java.lang.String = AbcDef
By the same rationale, why does something like 1.+(1) return a double 2.0?
scala> 1.+(1)
res1: Double = 2.0
Also, why does passing the argument "1" as a parameter result in "1.01" as follows:
scala> 1.+("1")
res9: String = 1.01
Why is the returned result a String instead of an effort for "1" to me transformed into the callers type?
Thanks
If you try that on Scala 2.10.0, you'll get a clue as to the answer:
scala> 1.+(1)
<console>:1: warning: This lexical syntax is deprecated. From scala 2.11,
a dot will only be considered part of a number if it is immediately
followed by a digit.
1.+(1)
^
Simply put, 1. is a valid Double in Scala (as it is in Java), so Scala is really doing this:
1. + (1)
That is, infix addition of a Double to an expression enclosed inside a (redundant) parenthesis.
As for the latter, Scala follows Java convention that anything added to a String results in a String and vice versa.
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