import scala.reflect.runtime.universe._
import scala.reflect.ClassTag
class A
class B
def foo[A](x: A) = typeOf[A] match {
case x:A => println("this an A")
case _ => println("no match")
}
}
但这将被证明是无用的,因为不可能匹配,我明白:
fruitless type test: a value of type runtime.universe.Type cannot also be a A
我想让foo
采用任何type
类,从基本类型到自定义类。我该怎么做?
最佳答案
您可以通过以下方式使用ClassTag
来实现它
import scala.reflect.ClassTag
def foo[A: ClassTag](x: A) = x match {
case x: A => println(s"this an ${x.getClass}")
case _ => println("no match")
}
A
可以是任何类型。
关于scala - 以任何对象作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41568058/