以下代码无法编译:
def f[T](conv: Option[String => T]) {}
f(Some(_.toInt))
使用 <console>:13: error: missing parameter type for expanded function ((x$1) => x$1.toInt)
报错,显式类型声明可以解决问题:
scala> f(Some((x: String) => x.toInt))
为什么编译器不能在这里推断字符串类型?是否存在某种歧义?
通常情况下,是否有可能手动检查和检查从下划线扩展生成的代码?
String
的变异或继承的类型类,那么在某些情况下可能会推断出它,但否则您只需传递一些ClassWithoutToInt
,并且它无法使用下划线推断。 - sebszyllerf(_.toInt) // show
,或者-Xprint:typer
来查看类型检查器如何看待你的代码。 - som-snytt