Double Definition Error Despite Different Parameter Types

走远了吗. 提交于 2019-12-01 22:04:31
Travis Brown

Here's a simpler example that shows the same issue:

object Example {
  def foo[T](f: Int => T) = ???
  def foo[T](f: String => T) = ???
}

This is equivalent to the following, after desugaring the => symbols:

object Example {
  def foo[T](f: Function[Int, T]) = ???
  def foo[T](f: Function[String, T]) = ???
}

The problem is that the Java Virtual Machine doesn't know about generics (in either Scala or Java), so it sees these two methods as the following:

object Example {
  def foo[T](f: Function) = ???
  def foo[T](f: Function) = ???
}

Which is clearly a problem.

This is one of many reasons to avoid method overloading in Scala. If that's not an option, you could use a trick like the following:

object Example {
  implicit object `Int => T disambiguator`
  implicit object `String => T disambiguator`

  def foo[T](f: Int => T)(implicit d: `Int => T disambiguator`.type) = ???
  def foo[T](f: String => T)(implicit d: `String => T disambiguator`.type) = ???
}

Which looks the same usage-wise, but is obviously pretty hideous.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!