scalaguiceclasstag

Reading type parameter's ClassType in trait


Let's say I have a trait Foo, with type parameter T, and I need a ClassTag of T to be used in Foo:

trait Foo[T] {
    implicit def ct: ClassTag[T]
}

I want to achieve that without implementing ct in every Foo implementation. e.g. I want to avoid having to this everytime:

class Bar extends Foo[String] {
    implicit def ct: ClassTag[String] = implicitly[ClassTag[String]]
}

Also, receiving the TypeTag implicit in the implementations constructor is not an option, since I use Guice for dependency injection, and it cannot handle the implicit type tag param in the constructor. So something like this is not an option:

class Bar(implicit val ct: ClassTag[String]) extends Foo[String]

Ideally I want something like this:

object Main extends App {
  trait Foo[T] {
    implicit def ct: ClassTag[T] = implicitly[ClassTag[T]]
  }

  class Bar extends Foo[String] {
    println(ct)
  }

  new Bar
}

But above's code end up in a StackOverflowError in runtime, since it calls itself recursively.


Solution

  • Can you use abstract class instead of trait?

    abstract class Foo[T](implicit val ct: ClassTag[T]) {
    }