prosseek
prosseek

Reputation: 190979

Storing and Instantiating a Scala class in a container/variable

I need to return a class based on the key string, and then instantiate the returned type. For example:

class A 
class B

val keyType = Map[String, Any ???] ("a" -> A, "b" -> B) ??? does not work
val t = keyType("a") ???
val i = ??? instantiate type A

However, "a" -> A does not work, furthermore, I'm not sure how to instantiate the class stored in a variable t.

What could be the solution.

Upvotes: 1

Views: 110

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 160005

First, classOf is available inside of Predef, so to make a Map[String, Class] you simply need to call it, parameterized with the type you need to access:

val keyType: Map[String, Class[_]] = Map("a" -> classOf[A], "b" -> classOf[B])
val t = keyType("a")
// t is a Class[_ >: B with A <: Object]

Second, all classes have a newInstance method (courtesy of inheriting from java.lang.Class), so you can just call that method:

val i = t.newInstance
// This assumes that you don't need to provide any arguments

Upvotes: 4

Related Questions