views:

95

answers:

1

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?

+10  A: 

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.

Randall Schulz
I'm going to take this excellent answer as a clue that it cannot be done with a trait.
Fred Haslam
Sorry, I should have pointed that out. "traits cannot have type parameters with context bounds" (quoth the compiler)
Randall Schulz