考虑以下两个代码片段:
scala> def f1(x:Any) = x match { case i:String => i; case _ => null }
f1: (x: Any)String
scala> def f2(x:Any) = x match { case i:Int => i; case _ => null }
f2: (x: Any)Any
Run Code Online (Sandbox Code Playgroud)
为什么是f2回归类型Any,f1而是String?我期待要么返回Any要么f2返回Int.
mic*_*ebe 12
如果方法返回不同的类型,则类型推断选择最低的公共超类型.
你的函数f1返回一个String或者null,哪个常见的超类型是String因为a String可以有值null.字符串是的子类AnyRef和AnyRefS可有null值.
你的函数f2返回一个Int(子类AnyVal)或者null常见的超类型Any.Int不可能null.
有关Scala的类层次结构,请参阅http://docs.scala-lang.org/tutorials/tour/unified-types.html.
另一个例子:
scala> def f3(b: Boolean) = if (b) 42
f: (b: Boolean)AnyVal
Run Code Online (Sandbox Code Playgroud)
f3 回报
42 b是true
或者()如果b是false.
所以它返回的类型是Int和Unit.常见的超类型是AnyVal.