F.X.
F.X.

Reputation: 7327

Creating an object from a type parameter in Scala

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

Answers (1)

R&#233;gis Jean-Gilles
R&#233;gis Jean-Gilles

Reputation: 32729

This can be done using ClassManifests, 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

Related Questions