Difference between matching String and Int in Scala
Consider the following two fragments of code:
scala> def f1(x:Any) = x match { case i:String => i; case _ => null }
f1: (x: Any)String
scala> de开发者_运维百科f f2(x:Any) = x match { case i:Int => i; case _ => null }
f2: (x: Any)Any
Why is f2
's return type Any
, while f1
's is String
? I was expecting either both to return Any
or f2
to return Int
.
The type inference chooses the lowest common supertype if a method returns different types.
Your function f1
returns a String
or null
, which common supertype is String
because a String
can have the value null
. String is a subclass of AnyRef
and AnyRef
s can have null
values.
Your function f2
return an Int
(subclass of AnyVal
) or null
, which common supertype is Any
. Int
cannot be null
.
See http://docs.scala-lang.org/tutorials/tour/unified-types.html for Scala´s class hierarchy.
Another example:
scala> def f3(b: Boolean) = if (b) 42
f: (b: Boolean)AnyVal
f3
returns
either 42 is b
is true
or ()
if b
is false
.
So the types it returns are Int
and Unit
. The common supertype is AnyVal
.
精彩评论