重载功能导致“扩展函数缺少参数类型”错误

时间:2015-04-08 20:21:56

标签: scala generics type-inference overloading

我有以下内容:

class FooList[T] (data: List[T]) {
  def foo (f: (T, T) => T, n: Int) = data.reduce(f)
  def foo (f: (T, T) => T, s: String) = data.reduce(f)
}

class BarList[T] (data: List[T]) {
  def bar(f: (T, T) => T, n: Int) = data.reduce(f)
}

BarList工作正常,FooList失败:

scala> new FooList(List(1, 2, 3)).foo(_+_, 3)
<console>:9: error: missing parameter type for expanded function ((x$1, x$2) => x$1.$plus(x$2))
          new FooList(List(1, 2, 3)).foo(_+_, 3)

scala> new FooList(List(1, 2, 3)).foo(_+_, "3")
<console>:9: error: missing parameter type for expanded function ((x$1, x$2) => x$1.$plus(x$2))
          new FooList(List(1, 2, 3)).foo(_+_, "3")
                                         ^
scala> new BarList(List(1, 2, 3)).bar(_+_, 3)
res2: Int = 6

为什么FooList.foo无效?

有没有办法让两个FooList调用同时工作?

1 个答案:

答案 0 :(得分:2)

似乎类型推断仅在选择适当的重载方法后确定_ + _的类型,因此它在静态分派之前需要它;但是有解决方法:

class FooList[T] (data: List[T]) {
  def foo (n: Int)(f: (T, T) => T) = data.reduce(f)
  def foo (s: String)(f: (T, T) => T) = data.reduce(f)
}

scala> new FooList(List(1, 2, 3)).foo(3)(_ + _)
res13: Int = 6

scala> new FooList(List(1, 2, 3)).foo("3")(_ + _)
res14: Int = 6

如果您不想更改客户端的API,则可以合并两个重载方法(第二个参数变为union type然后):

class FooList[T] (data: List[T]) {
   def foo[A] (f: (T, T) => T, NorS: A)(implicit ev: (Int with String) <:< A) = NorS match {
      case n: Int => data.reduce(f)
      case s: String => data.reduce(f)
   }
}

scala> new FooList(List(1, 2, 3)).foo(_ + _, "3")
res21: Int = 6

scala> new FooList(List(1, 2, 3)).foo(_ + _, 3)
res22: Int = 6

scala> new FooList(List(1, 2, 3)).foo(_ + _, 3.0)
<console>:15: error: Cannot prove that Int with String <:< Double.
              new FooList(List(1, 2, 3)).foo(_ + _, 3.0)
                                            ^

因此调度正在转移到运行时,但实际接口保持不变。