Double Definition Error Despite Different Parameter Types

后端 未结 1 1820
长情又很酷
长情又很酷 2021-01-21 09:58

I\'m receiving a double definition error on the following two methods:

def apply[T](state: T, onRender: T => Graphic,
             onMouseEvent: (MouseEvent,          


        
相关标签:
1条回答
  • 2021-01-21 10:37

    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.

    0 讨论(0)
提交回复
热议问题