Creating TypeLiterals in Scala

August 30, 2010

In case anyone wondered, here is how one can easily create instances of Google Guice’s TypeLiteral in Scala. Type literals are used for reifying types.

def typeLiteralOf[T](implicit m: scala.reflect.Manifest[T]): TypeLiteral[T] = (m match {
  case m: ClassManifest[T] if m.typeArguments.isEmpty =>
  case m: ClassManifest[T] =>
    TypeLiteral.get(new ParameterizedTypeImpl(m.erasure, {
      case n: ClassManifest[_] => typeLiteralOf(n).getType

ParameterizedTypeImpl is part of our code base, but a similar implementation is defined in Guice’s MoreTypes class.

We can then use the typeLiteralOf function like this:


Careful though, this implementation does not cover all cases. Check out scala-guice for a bullet-proof version.