Reputation: 2755
Is it possible in Scala to pass a type to a function as an argument (along with other parameters) and return an object of that type?
For example, let's say I have n different classes where each of them has its own members. I want some thing like:
def Make(T:TypeOfPossibleClasses):T={
val A= new T()
// do some thing on A
A
}
I'm aware of Manifest
, and I know that I can do this by matching manifest of T
with manifest of all possible classes of interest. But, I may have too many classes (and in fact new class types may get introduced later on).
Does Scala support generic type passing?
Thanks!
Upvotes: 1
Views: 84
Reputation: 10681
I suppose you can act like in java
def make[T](clz: Class[T]): T = clz.newInstance() // class should have default constructor
make(classOf[String])
or use Manifest
instance:
def make[T](implicit m : Manifest[T]): T =
m.runtimeClass.asInstanceOf[Class[T]].newInstance()
make[String] // res0: String = ""
make[AnyRef] // res1: AnyRef = java.lang.Object@7794ed7a
Upvotes: 3