Yann Moisan
Yann Moisan

Reputation: 8281

How to call a polymorphic function with a val

Given the following polymorphic method

def get[T](implicit m: ClassTag[T]) : Seq[T]

How can I call with the parameter from a val. Unfortunately the following doesn't compile :

val clazz = Class[Int]
get[clazz]

[update] I was trying to do :

val classes = List(String.getClass, Int.getClass)
classes.map { c => get(ClassTag(c)) }

Upvotes: 0

Views: 107

Answers (3)

Arpit Aggarwal
Arpit Aggarwal

Reputation: 29316

You can directly call it as :

 val result = get[Int](ClassTag[1]);

Upvotes: 0

Michael Zajac
Michael Zajac

Reputation: 55569

You can't supply a type parameter with a val like that, nor is Class[Int] a value. It's unclear what you really want to do.

You could use a type alias:

type C = Int
get[C]

You could explicitly look for a ClassTag using classTag[A], which is essentially the same as providing a type hint to get[A]:

get(classTag[Int])

You could also get the ClassTag from a class instance, and explicitly pass it:

val ct: ClassTag[Int] = ClassTag(1.getClass)
get(ct)

None of these seem particularly useful.

Upvotes: 1

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179209

Not sure what you're trying to achieve, but you can use a type alias:

type clazz = Class[Int]

Upvotes: 0

Related Questions