在试图理解Scala的同时,我遇到了这个类型的推断问题:
object Demo extends App {
  def demo(f: (Int, Int) => Int) = ???
  demo((a: Int) => 42)
  demo((a) => 42) // <-- any tricks to make this compile?
  implicit def f1Tof2(f: Int => Int): (Int, Int) => Int =
    (a: Int, b: Int) => f.apply(a)
}编译器无法正确推断类型的原因是什么?有什么诀窍可以让它发挥作用吗?
发布于 2016-03-24 23:15:37
这是不可能的当您调用demo((a, b) => a + b) (例如)时,编译器已经在期待一个(Int, Int) => Int,因此它将推断(a, b) => a + b为(Int, Int) => Int,因为它具有正确的形状。
但是,当调用demo(a => 42)时,编译器将Function1[?, Int]视为参数,而不指明参数类型是什么。由于demo需要一个Function2,所以编译的唯一方法是编译器能够找到从传递的参数类型到(Int, Int) => Int的隐式转换。但它不能,因为它不知道它是从哪种类型转换的。它不能仅仅假设它将是一个Int => Int。
只有两种方法才能使这件事奏效。
1.)像您已经做的那样,显式声明匿名函数的参数类型。这是应用隐式转换的唯一方法。
demo((a: Int) => 42)2.)为接受demo的Int => Int提供重载。
def demo(f: (Int, Int) => Int): Int = f(1, 2)
def demo(f: Int => Int): Int = demo((a, b) => f(a))
scala> demo(a => 42)
res3: Int = 42https://stackoverflow.com/questions/36210053
复制相似问题