Search code examples
scalaimplicit

Is there a way an implicit class can override a default implementation


Say I define the following:

class A {
    def foo() = println("A::foo")
}

implicit class Wrapper(a: A) {
    def foo() = println("Wrapper::foo")
    def bar() = println("Wrapper::bar")
}

val a = new A
a.foo()
a.bar()

A::foo() is the method that is called. Is there any possible way an implicit class can override the default implementation in A?


Solution

  • If a member method exists then compiler would not search for implicit. If overriding with inheritance is not an option, you might consider "turning the tables" and create a delegate like so

    class A {
      def foo() = println("A::foo")
      def zar() = println("A::zar")
    }
    
    class Wrapper(val a: A) {
      def foo() = println("Wrapper::foo")
      def bar() = println("Wrapper::bar")
    }
    
    implicit def unwrap(wrapped: Wrapper): A = wrapped.a
    
    val a = new Wrapper(new A)
    a.zar()   // A::zar
    a.foo()   // Wrapper::foo
    a.bar()   // Wrapper::bar