Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in scala to produce a generic instance without an example instance?

I was playing with creating a generic factory as follows:

trait Factory[T] { def createInstance():T = new T() }
val dateFactory = new Factory[Date](){}
val myDate = dateFactory.createInstance()

The 'new T()' doesn't compile, as T is undefined until runtime. I know that I can get it to work by passing in an instance of the class to some method (ie. createInstance(classOf[Date]) )

I am asking if there is some introspection magic that could replace 'new T()' so that I can create my super simple factory?

like image 294
Fred Haslam Avatar asked Aug 20 '10 19:08

Fred Haslam


1 Answers

This will work:

class Factory[T : ClassManifest] {
  def
  createInstance(): T =
    (implicitly[ClassManifest[T]]).erasure.newInstance.asInstanceOf[T]
}

if the class for which it is instantiated has a default (zero-arg) constructor.

like image 69
Randall Schulz Avatar answered Sep 20 '22 02:09

Randall Schulz