0

In the minimal type class example below, scala 2.12.6 / sbt 1.2.1 complains could not find implicit value for parameter tc: tryout.Tryout.TypeClassTrait[Int]. If I uncomment the println line, it compiles. I was expecting this to work without the println because I import everything from the companion object.

Is this a bug or a feature? (By the way: Setting the scalac option -Xlog-implicits did not produce anything helpful.)

trait Tryout {
  import Tryout._
//  println(IntTypeClass) // uncomment this line to make compile work
  show(3)                 // compile fails here
}
object Tryout {
  trait TypeClassTrait[T] {
    def show(t: T): Unit
  }
  implicit object IntTypeClass extends TypeClassTrait[Int] {
    override def show(t: Int): Unit = println(t)
  }
  def show[T](t: T)(implicit tc: TypeClassTrait[T]): Unit = tc.show(t)
}
Georg
  • 966
  • 8
  • 25
  • 1
    See https://stackoverflow.com/questions/20380800/scala-implicits-resolution-mechanism-is-declaration-order-dependent, https://stackoverflow.com/questions/12777513/order-of-defintion-matters-in-scala, and https://stackoverflow.com/questions/32438750/how-does-scala-use-explicit-types-when-resolving-implicits. Probably quite a few others, too. – Alexey Romanov Aug 28 '18 at 12:13
  • 1
    I agree it's kind of duplicating. TL;DR : declare the trait after the object, and you'll be good to go. – C4stor Aug 28 '18 at 12:34
  • 1
    Possible duplicate of [Scala implicits resolution mechanism is declaration order dependent?](https://stackoverflow.com/questions/20380800/scala-implicits-resolution-mechanism-is-declaration-order-dependent) – C4stor Aug 28 '18 at 12:35
  • @AlexeyRomanov thanks for the references - in particular the second one leading to the Scala compiler bug was enlightening. If you post it as answer, I will accept it. (Thanks to C4stor as well, but Alexey was faster :) ) – Georg Aug 28 '18 at 13:08
  • 1
    @Georg We don't point to duplicates to duplicate answers, if the question is already answered there, it doesn't need one more :) – Alexey Romanov Aug 28 '18 at 16:00

0 Answers0