1
votes

I have the following traits:

trait Tr1 {
  implicit val i: Int
}

trait Ctx { tr: Tr1 =>
  def test: Int = implicitly[Int]
}

And now I'm running my application as follows:

  def main(args: Array[String]): Unit = {
    val ctx: Ctx = new Ctx with Tr1 {
      override implicit val i: Int = 123
    }
    println(ctx.test) //prints 123!!!
  }

Surprisingly it prints 123. I thought that we have val i deafultly initialized to 0 but compiler figured out that we have and instance which overrides implicit val i: Int to the value 123.

Now I'm confused about implicit resolution in such cases. Can you please exaplain?

1

1 Answers

1
votes

trait Ctx { tr: Tr1 it's a self type, it means it requires Tr1 for Ctx like extend it, and implicitly[Int] it's trying to find a implicit Int variable. Since Tr1 has defined a implicit val i variable, so compiler can infer implicitly[Int] is implicit val i in current scope.

So when you override implicit val i: Int = 123, the test method will return 123.