开发者

What is the type that the Scala REPL prints?

When I create a small Map in the repl, it tells me that its type is immutable.Map

scala> Map(1->1, 2->2)                                    
res8: scala.collection.immutable.Map[Int,Int] = Map((1,1), (2,2))

This isn't the whole truth though, as in this case

scala> Map(1->1, 2->2).getClass
res9: java.lang.Class[_] = class scala.collection.immutable.Map$Map2

How does Scala decide what to print as the type of a开发者_C百科n expression?


The short answer is that the Scala REPL prints the static type of your results, as inferred from your expression Map(1->1, 2->2), and getClass returns the dynamic type, which can be a subtype of the static type.

A longer answer would be about how Scala's type inference engine works. You'll maybe want to read the relevant sections in the Scala Language Reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜