【发布时间】:2017-06-05 16:09:19
【问题描述】:
鉴于以下两个 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)
为什么 Scala 认为 toList 函数是 Nothing => List[Nothing] 而不是 Int => List[Int]?
【问题讨论】:
-
在这种情况下,推理引擎需要一点帮助:
foo[Int](toList, 34)或foo(toList[Int], 34)
标签: scala parametric-polymorphism