Reputation: 7327
I want to create a method that takes a type parameter, obviously with no parameters on its constructor, and returns a dummy object constructed with that constructor. Basically some kind of factory pattern.
Code example :
trait Model
class A extends Model
class B extends Model
def dummy[T <: Model] = new T // Fails compilation with "class type required but T found"
dummy[A] // Returns an instance of A
dummy[B] // Returns an instance of B
Upvotes: 1
Views: 1331
Reputation: 32729
This can be done using ClassManifest
s, which are designed to overcome erasure:
def dummy[T <: Model : ClassManifest] = classManifest[T].erasure.newInstance
As for doing it at compile time without reflection, I guess that it could be done using scala 2.10 macros.
Upvotes: 4