Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

Scala String vs java.lang.String - type inference

In the REPL, I define a function. Note the return type.

scala> def next(i: List[String]) =  i.map {"0" + _} ::: i.reverse.map {"1" + _}
next: (i: List[String])List[java.lang.String]

And if I specify the return type as String

scala> def next(i: List[String]): List[String] = i.map {"0" + _} ::: i.reverse.map {"1" + _}
next: (i: List[String])List[String]

Why the difference? I can also specify the return type as List[Any], so I guess String is just a wrapper supertype to java.lang.String. Will this have any practical implications or can I safely not specify the return type?

question from:https://stackoverflow.com/questions/6559938/scala-string-vs-java-lang-string-type-inference

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a very good question! First, let me assure you that you can safely specify the return type.

Now, let's look into it... yes, when left to inference, Scala infers java.lang.String, instead of just String. So, if you look up "String" in the ScalaDoc, you won't find anything, which seems to indicate it is not a Scala class either. Well, it has to come from someplace, though.

Let's consider what Scala imports by default. You can find it by yourself on the REPL:

scala> :imports
 1) import java.lang._             (155 types, 160 terms)
 2) import scala._                 (801 types, 809 terms)
 3) import scala.Predef._          (16 types, 167 terms, 96 are implicit)

The first two are packages -- and, indeed, String can be found on java.lang! Is that it, then? Let's check by instantiating something else from that package:

scala> val s: StringBuffer = new StringBuffer
s: java.lang.StringBuffer =

scala> val s: String = new String
s: String = ""

So, that doesn't seem to be it. Now, it can't be inside the scala package, or it would have been found when looking up on the ScalaDoc. So let's look inside scala.Predef, and there it is!

type String = String

That means String is an alias for java.lang.String (which was imported previously). That looks like a cyclic reference though, but if you check the source, you'll see it is defined with the full path:

type String        = java.lang.String

Next, you might want to ask why? Well, I don't have any idea, but I suspect it is to make such an important class a little less dependent on the JVM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...