Here is my code
package a1
trait Algorithm[T] {
def someMethod(a: Int): T
}
package b2
import a1.Algorithm
class Word2Vec[T] extends Algorithm[T] {
def someMethod(a: Int): T = a.asInstanceOf[T]
}
package c3
import a1.Algorithm
object Main {
def main(args:Array[String]) = {
val word2vec:Algorithm[Float] = Class.forName("b2.Word2Vec").newInstance().asInstanceOf[Algorithm[Float]]
val a = word2vec.someMethod(123)
println(a)
}
}
and I got this:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
at scala.runtime.BoxesRunTime.unboxToFloat(BoxesRunTime.java:107)
at c3.Main$.main(Main.scala:8)
at c3.Main.main(Main.scala)
by the way,How could I get a type when I get a string name. I have an "int" and I want to pass type Int as the type parameter for generic
asInstanceOfis a big code smell especially in this case it seems it will never work. - Finally, how did you expect it to work if you passed an Int and asked for a Float?Intand asked for aFloat?"Intis passed todef someMethod(a: Int)...andFloatisTinWord2Vec[T]. There's no problem in castingscala.Inttoscala.Float:123.asInstanceOf[Float]. It'sjava.lang.Integerthat can't be casted tojava.lang.Float.