鉴于以下两个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