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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With