Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Last active January 20, 2019 08:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anoopelias/4462155 to your computer and use it in GitHub Desktop.
Save anoopelias/4462155 to your computer and use it in GitHub Desktop.
Using Manifest to get around with type erasure in scala

Typically, you can't use a 'new' operator on a generic type. This is because of type erasure.

scala> def create[T] = new T
<console>:7: error: class type required but T found
   def create[T] = new T
                       ^

Scala gives a way of getting around this problem, with the Manifest class.

scala> def create[T](implicit m:Manifest[T]) = m.erasure.newInstance
create: [T](implicit m: Manifest[T])Any

scala> create[String]
res0: Any = ""

scala> class SomeClass
defined class SomeClass

scala> create[SomeClass]
res1: Any = SomeClass@112356a

The implicit Manifest object passed by the compiler has the details of the generic at runtime. Using a bit more syntactic sugar, create can be rewritten as,

scala> def create[T:Manifest] = manifest[T].erasure.newInstance
create: [T](implicit evidence$1: Manifest[T])Any

This feature is useful in other cases also, like, getting the type of objects in a List at runtime.

scala> def processList[E : Manifest](ls : List[E]) = println(manifest[E].erasure)
processList: [E](ls: List[E])(implicit evidence$1: Manifest[E])Unit

scala> processList(List(1, 3, 5, 7))
int

scala> processList(List("A", "S", "D", "F"))
class java.lang.String
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment