【发布时间】:2016-07-12 15:01:18
【问题描述】:
在尝试掌握 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)
}
编译器无法正确推断类型的原因是什么?有什么技巧可以让它发挥作用?
【问题讨论】:
-
确保还包括相关消息。
-
好点!编译错误是“缺少参数类型”。
-
在我的例子中编译器说:
wrong number of parameters: expected 2.Compiler 不知道(a)的类型是Int(因为它没有指定),所以它不能隐式应用。 -
如果 a 是泛型类型,那么您需要创建一个泛型 f1Tof12 方法
标签: scala types type-conversion