gardenhead
gardenhead

Reputation: 2497

In Scala, is it possible for me to dynamically specify the type parameter of a parametric type?

I am writing a program where the user specifies the path to a class on the command line. I turn it into a Class object via:

val clazz = Class.forName(args([0]))

I have a parametric class MyParametric[T] with a single type parameter. I then want to make another Class type Class[ParamatricType[clazz] so I can pass that to a method, e.g. I want to do something like

myMethod(classOf[ParametricType[clazz]])

but that is not allowed. How can I instantiate a parametric type with the type parameter being given dynamically?

Upvotes: 2

Views: 355

Answers (4)

Alexey Romanov
Alexey Romanov

Reputation: 170735

If you need to do something more than classOf (which the other answers already handle) and can modify ParametricType, one approach would be (depending on the details of what you actually need):

import scala.reflect.ClassTag
class ParametricType[T](implicit val tag: ClassTag[T])

val clazz: Class[_] = ...
myMethod(new ParametricType()(ClassTag(clazz)))

Upvotes: 0

sebszyller
sebszyller

Reputation: 853

From the information you provided it's hard to tell whether the user will specify from the set of known classes (e.g. fruits) or any class imaginable. However, you could use pattern matching with different classes during the assignment and handle that according to the type.

Upvotes: 0

Rex Kerr
Rex Kerr

Reputation: 167891

ParametricType's type parameter will be erased, so the value of classOf[ParametricType[_]] will be the same no matter what you plug in for _ (including _).

The type won't be the same of the classOf won't be the same as that isn't erased (the compiler keeps track at compile time). You could refer to the singleton type clazz.type, but it's not clear what that will buy you.

Upvotes: 1

sjrd
sjrd

Reputation: 22085

If you want to use it as the argument to classOf, you don't even need the type parameter. You can just use _, because type parameters are erased at run-time in Scala:

myMethod(classOf[ParametricType[_]])

Upvotes: 1

Related Questions