问题
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.
- Is that even possible in Scala?
- Is that a good idea? Any better pattern if it is not?
- Is there a way to achieve this at compile-time only (i.e. without reflection)?
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
回答1:
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.
来源:https://stackoverflow.com/questions/15861441/creating-an-object-from-a-type-parameter-in-scala