简体   繁体   中英

Overloaded function causes “missing parameter type for expanded function” error

I have the following:

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 works fine, FooList fails:

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

Why doesn't FooList.foo work?

Is there any way to get the two FooList calls to both work?

It seems like type inference determines the type of _ + _ only after choosing appropriate overloaded method, so it requires it explicitly before static dispatch; however there is the workaround:

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

If you don't want to change the API for clients, you may merge two overloaded methods (second parameter becomes a union type then):

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)
                                            ^

So dispatching is moving to runtime here, but actual interface remains the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM