【发布时间】:2011-03-19 22:45:43
【问题描述】:
我在 Scala 中有 this class:
object Util {
class Tapper[A](tapMe: A) {
def tap(f: A => Unit): A = {
f(tapMe)
tapMe
}
def tap(fs: (A => Unit)*): A = {
fs.foreach(_(tapMe))
tapMe
}
}
implicit def tapper[A](toTap: A): Tapper[A] = new Tapper(toTap)
}
现在,
"aaa".tap(_.trim)
无法编译,报错
错误:缺少扩展函数的参数类型 ((x$1) => x$1.trim)
为什么类型不是推断为String?从错误看来,隐式转换确实会触发(否则错误将类似于“tap 不是String 类的成员”)。而且看来转换必须是Tapper[String],也就是说参数的类型是String => Unit(或(String => Unit)*)。
有趣的是,如果我注释掉tap 定义中的任何一个,它就会编译。
【问题讨论】:
标签: scala overloading type-inference overload-resolution