简体   繁体   中英

What's behind this implicit cast in Scala?

I'm not familiar with Scala and come across this problem below when using interactive mode:

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

What I'm curious about is that how the type of the result can be different( java.lang.String vs String ). And in Book Seven Languages in Seven Weeks the two types are both java.lang.String .

BTW,the version of scala interpreter is 2.9.1.

On the JVM, scala's String is just an alias to java.lang.String . The fact that the Repl sometimes displays the type as String and sometimes as java.lang.String is just a minor (REPL specific) glitch that does not affect in any way the runtime behaviour.

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

What do you want ???

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 the Interactive Interpreter just says String not java.lang.String . But we have java.lang.String instances.

("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.

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

This looks so dirty

I don't think so.

should be consistent so that they would always be String

I don't think so. It is consistent.

java version "1.7.0_09"

Scala code runner version 2.9.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM