Creating TypeLiterals in Scala

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 =>
    TypeLiteral.get(m.erasure)
  case m: ClassManifest[T] =>
    TypeLiteral.get(new ParameterizedTypeImpl(m.erasure, m.typeArguments.map {
      case n: ClassManifest[_] => typeLiteralOf(n).getType
    }.toArray))
}).asInstanceOf[TypeLiteral[T]]

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:

injector.getInstance(Key.get(typeLiteralOf[List[String]]))

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