2

Given a case class and companion object like below:

case class Example(a: String)

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

How to make the implicit method compile? In other words, is it possible to refer to the current instance that the implicit method has been called upon?

Marek M.
  • 3,799
  • 9
  • 43
  • 93
  • 1
    `concat` cannot be called upon an instance of `Example`. As a result there is no instance in scope for `this` to refer to. – ziggystar Dec 17 '19 at 08:50
  • There is already something similar asked: https://stackoverflow.com/questions/36528736/case-class-and-companion-object – amer Dec 17 '19 at 08:55
  • @amer, it's similar but doesn't quite answer my question. – Marek M. Dec 17 '19 at 08:59

1 Answers1

6

I think what you want is the following:

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

or using an anonymous implicit class

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

Usage

You can then use it like this

import Foo._

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

Import and companion object

If the object is called Example, then it becomes the companion object for class Example, and you do not have to import Foo._ to use the extension method.

ziggystar
  • 28,410
  • 9
  • 72
  • 124