Reputation: 1584
I have some code to instantiate a random class like this:
trait T
class A extends T
class B extends T
class C extends T
def createRandomT = {
val choices = Vector(classOf[A], classOf[B], classOf[C])
val cls = new scala.util.Random().shuffle(choices).head
instantiateT(cls)
}
def instantiateT(cls: Class[_ <: T]) = {
ClassManifest.fromClass(cls) match {
case c if c <:< classManifest[A] => new A
case c if c <:< classManifest[B] => new B
case c if c <:< classManifest[C] => new C
}
}
This works, but after upgrading to 2.10 instantiateT
gives various deprecation warnings.
Any hints how to replicate the functionality with ClassTag
and/or TypeTag
?
Edit: As pointed out by Daniel this works:
cls match {
case c if c.isAssignableFrom(classOf[A]) => new A
case c if c.isAssignableFrom(classOf[B]) => new B
case c if c.isAssignableFrom(classOf[C]) => new C
}
Upvotes: 2
Views: 1255
Reputation: 32719
I am not sure why it has to be so complicated...
Surely if you already have a Class
instance you can just call Class.newInstance
? Like so:
def instantiateT(cls: Class[_ <: T]) = cls.newInstance
Or maybe you are performing a match because in your real code each class has a separate list of (default) argument to pass to the constructor?
Upvotes: 2
Reputation: 297195
If you've got a Class
, you should just use isAssignableFrom
.
case c if cls.isAssignableFrom(c.getClass()) => new A
Upvotes: 2