What is behind this implicit cast in Scala?

I am not familiar with Scala and encounter this problem below when using interactive mode:

scala>"abc"+4 res0: java.lang.String = abc4 scala>4+"abc" res1: String = 4abc 

What interests me is how the type of the result may be different ( java.lang.String vs String ). And in the book "Seven Languages ​​in Seven Weeks" there are two types: java.lang.String .

BTW, the Scala interpreter version is 2.9.1.

+4
source share
2 answers

In the JVM, scala String is just an alias for java.lang.String . The fact that Repl sometimes renders the type as String , and sometimes as java.lang.String is just a minor (REPL specific) crash that does not affect runtime behavior.

For what it's worth, here is what I get in scala 2.10-RC1:

 scala> "abc"+4 res0: String = abc4 scala> 4+"abc" res1: String = 4abc 
+6
source

What you need???

 scala> (4+"abc").getClass.getName res3: java.lang.String = java.lang.String scala> ("abc"+4).getClass.getName res5: java.lang.String = java.lang.String 

Both are java.lang.String. I think Interactive Interpreter just says String not java.lang.String . But we have instances of java.lang.String.

("abc"+4): '+' is applied to java.lang.String, and returns java.lang.String. This is true both on Java and Scala.

(4+"abc") on Java: '+' is applied to java.lang.Integer, and returns java.lang.String.

(4+"abc") on Scala: '+' is applied to scala.Int, and returns String. '+(x: String)' is defined on scala.Int.

The output of Interactive Interpreter uses type String = java.lanag.String , which is defined on Predef.scala. Of course, the reverse is not defined.

It looks so dirty

I do not think so.

must be consistent so that they are always String

I do not think so. It is agreed.

java version "1.7.0_09"

Scala code version 2.9.2

0
source

Source: https://habr.com/ru/post/1445793/


All Articles