user79074
user79074

Reputation: 5270

Best way to define an implicit class that needs a parameter at runtime

I have an implicit class that needs to use a given parameter at runtime. So I define this implicit in another class that takes this parameter in the constructor. A simplified version of what I am doing is as follows:

case class A(p1: String) {
    def foo = println("foo: " + p1)
}

class B(p2: String) {
    implicit class Enhancer(a: A) {
        implicit def bar = s"bar: ${a.p1}, $p2"
    }
}

So when I need to use this class I then do the following:

val a = A("x")

val b = new B("y")
import b._

a.bar

I am wondering if there is a neater way than the above? Specifically the middle two lines where I define the object and then import from it. For example is there any way I could have a one line call to return the implicit class I need?

Upvotes: 0

Views: 71

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

Try to add implicit parameter to Enhancer.

case class A(p1: String) {
  def foo = println("foo: " + p1)
}

class B(val p2: String)

implicit class Enhancer(a: A)(implicit b: B) {
  implicit def bar = s"bar: ${a.p1}, ${b.p2}"
}

val a = A("x")

implicit object b extends B("y")

a.bar

or

implicit val b = new B("y")

a.bar

Or

implicit class Enhancer(val a: A) extends AnyVal {
  implicit def bar(implicit b: B) = s"bar: ${a.p1}, ${b.p2}"
}

Upvotes: 3

Related Questions