有没有办法隐式 class 可以覆盖默认实现

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

假设我定义如下:

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() 是被调用的方法。是否有任何可能的方法,隐式 class 可以覆盖 A 中的默认实现?

如果存在一个成员方法,那么编译器would not search for implicit. If overriding with inheritance is not an option, you might consider "turning the tables" and create a delegate就像这样

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