鑑於以下兩個Scala函數,兩者都按預期進行編譯。Scala多態函數會編譯但不會按預期運行
scala> def toList[A](a: A) = List(a)
toList: [A](a: A)List[A]
scala> def foo[A](f: A => List[A], b: A) = f(b)
foo: [A](f: A => List[A], b: A)List[A]
然而,當你運行它,它給了以下錯誤信息:
scala> foo(toList, 12)
<console>:14: error: type mismatch;
found : Nothing => List[Nothing]
required: Int => List[Int]
foo(toList, 12)
爲什麼斯卡拉認爲toList
功能是Nothing => List[Nothing]
而不是Int => List[Int]
?
在這種情況下,推理引擎需要一些幫助:'foo [Int](toList,34)'或'foo(toList [Int],34)' – jwvh