Search code examples
scalaoverloadingtype-erasure

Why does overloading polymorphic methods with different upper bounds not compile in Scala


Why does the following not compile in Scala:

class A
class B

object X {
  def f[Q <: A](q: Q): Q = q
  def f[Q <: B](q: Q): Q = q
}

with error message

<console>:16: error: method f is defined twice
  conflicting symbols both originated in file '<console>'
         def f[Q <: B](q: Q): Q = q

To my understanding, after type erasure, def f[Q <: A](q: Q): Q should be replaced with its upper bound: def f(q: A): Any and the second overloaded f correspondingly. So they should be distinguishable after type erasure.

So why does Scala complain anyway?


Solution

  • Re-posting comment as an answer to improve visibility.

    I found this old post about what seems to be the same issue: http://www.scala-lang.org/old/node/4625.html

    It seems to be a known issue with the Scala compiler, having to do more with the fact that it would be difficult to support this feature without breaking other (Scala-only) features and guarantees of the compiler. The post also shows few workarounds.

    It would be very interesting if any compiler guru here on SO were able to shed some light on whether Dotty - or should I say Skala? ;) - will plan on fixing it.