Search code examples
scalaimplicits

Class with its own context bound


The following works:

trait Context[T] {
    def context(x: T): String

class Foo[T : Context](x: T) {
    def bar() = implicitly[Context[T]].context(x)
}

implicit val c = new Context[Double] { 
    override def context(x: Double): String = "I am a double"
}

val f = new Foo(2.0)
f.bar() // I am a double

So I thought... is it also possible if I construct a class who has its own Context definition in it?

object Foo {
    def apply[T : Context](x: T) = new Foo[T](x)
    def apply[T](x: T, contextFunc: T => String): Foo[T] with Context[T] = new Foo[T](x) with Context[T] {
        override def context(x: T): Double = contextFunc(x)
    }
}

val f2 = Foo[Double](2.0, x => "I am still a double")

But it starts complaining that the implicit evidence is missing in the 2nd apply function. I can imagine that, since it looks like it starts to make the Foo-class first and then start to make the Context[T] trait.

Is there a way to solve this? In other words? Is there a way to construct a Foo class that has its own Context[T]?


Solution

  • The simplest way is probably to construct a context object and explicitly pass it as an argument, when constructing Foo:

    def apply[T](x: T, contextFunc: T => String): Foo[T] = 
      new Foo(x)(new Context[T] {
        def context(t: T) = contextFunc(t)
      })