Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Using Manifests in Scala to create a new instance of type T in a generic class February 5, 2011

Filed under: Scala — Rupert Bates @ 3:41 pm

To create a new instance of T in the class

class MyClass[T]

you can use the Manifest class as follows:

class MyClass[T](implicit man: Manifest[T]) {
  // get a new instance of T
  def getNewInstance =  man.erasure.newInstance
  // get Class[T]
  def getClassT = man.erasure.asInstanceOf[Class[T]]
}

What I initially didn’t get when I was trying to use this technique was how you can use it with a constructor which takes a non implicit argument. To do this you need the following syntax:

class MyClass[T](myConstructorParam : String)(implicit man: Manifest[T]) {
  // get a new instance of T
  def getNewInstance =  man.erasure.newInstance
  // get Class[T]
  def getClassT = man.erasure.asInstanceOf[Class[T]]
}
Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s