Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Using Manifest to get around with type erasure in scala

View Manifest.md

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
Something went wrong with that request. Please try again.