如何在隐式方法中引用 "this"

How to refer to "this" in an implicit method

给定一个案例 class 和如下所示的伴随对象:

case class Example(a: String)

object Example {
  implicit def concat(b: String): Example =
    Example(this.a + b)
}

如何使隐式方法编译通过?换句话说,是否可以引用调用隐式方法的当前实例?

我想你想要的是:

object Foo {
  implicit class RichExample(val e: Example) {
    def concat(b: String): Example = Example(e.a + b)
  }
}

或使用匿名隐式 class

object Foo {
  implicit def richExample(e: Example) = new {
    def concat(b: String): Example = Example(e.a + b)
  }
}

用法

然后你可以像这样使用它

import Foo._

Example("foo").concat("bar")

导入和伴随对象

如果该对象被称为 Example,那么它将成为 class Example 的伴随对象,并且您不必 import Foo._ 使用扩展方法.