Igor Yudnikov
Igor Yudnikov

Reputation: 464

Scala class casting

I have:

var className = "scala.collection.immutable.List"
val clazz = Class.forName(className)
val value = ArrayBuffer(1, 2, 3)

so the question is how to cast value to class, if className is variable? I can't do

value.asInstanceOf[clazz.type]

but i can call

value.toList

and it does the job with implicit conversion method, but how i can find and invoke this method when className is variable?

Upvotes: 0

Views: 186

Answers (1)

user7820268
user7820268

Reputation: 26

I don't know a magical way to convert from ArrayBuffer to any collection, but you can call getMethod to locate and invoke the toList method:

val method = value.getClass.getMethod("toList")
method.invoke(value)  

An exception will be thrown if toList in not found in value. I would have preferred to comment my answer, but not enough reputation

Upvotes: 1

Related Questions