Scala typeclasses implicit resolution

Viewed 71

(Scala 2.11.8)

Consider the following code:

object ScalaTest extends App {
  class Wrapper {
    import Wrapper._

    def init(): Unit = {
      // "could not find implicit value for parameter tc: ScalaTest.Wrapper.TC[Int]"
      printWithTC(123)

      // Compiles
      printWithTC(123)(IntTC)

      // Compiles again!
      printWithTC(132)
    }
  }

  object Wrapper {
    trait TC[A] {
      def text(a: A): String
    }

    implicit object IntTC extends TC[Int] {
      override def text(a: Int) = s"int($a)"
    }

    def printWithTC[A](a: A)(implicit tc: TC[A]): Unit = {
      println(tc.text(a))
    }
  }

  (new Wrapper).init()
}

I have a bunch of questions regarding this piece of code:

  1. Why doesn't IntTC get resolved in the first place?
  2. Why it compiles after being used once? (if you comment out the first invocation, code works)
  3. Where should typeclass implicits be placed to get resolved properly?
2 Answers
Related