将 Scala 类作为参数传递? [英] Passing Scala Class as parameter?
问题描述
我希望将类作为参数传递给 Scala 函数,如下所示:
I'm looking to pass a Class as a parameter to a Scala function like so:
def sampleFunc (c : Class) : List[Any]
(附带问题:参数中的类型应该是 Class 还是 Class[_]?)
(Side question: should the type in the parameter be Class or Class[_]?)
我传递 Class 类型的原因是为了检查对象是否属于特定类型.目前,作为一种解决方法,我将一个示例对象传递给该方法并比较两个对象的 .getClass 结果.我几乎不认为这是理想的,而且我确信在 Scala 中有一种明确定义的传递类型的方法.
The reason I'm passing a Class type is to check whether an object belongs to a particular type or not. At the moment, as a workaround, I'm passing a sample object to the method and comparing the two object's .getClass result. I hardly think this is ideal though and I'm sure there's a clearly defined way of passing Types in Scala.
推荐答案
好吧,对于您最初的问题:是的,您可以将 Scala 类作为参数传递.由于 Class
是一个类型构造器,它需要一个具体的类型来创建一个类型以用于参数.您可以像以前一样使用通配符存在类型 Class[_]
.
Well, to your original question: Yes, you can pass Scala Class as an argument.
As Class
is a type constructor, it needs a concrete type to make a type to be used in argument. You can use the wildcard existential type Class[_]
as you have done.
def sample(c: Class[_]) = println("Get a class")
sample(classOf[Int])
但是,如果你想检查一个对象是否是某种类型,我建议你使用=:=
,结合默认参数
However, if you want to check whether an object is of certain type, I recommend you to use =:=
, in combination with default parameter
def checkType[T](obj: T)(implict ev: T =:= Int = null) =
if (ev == null) "get other"
else "get int"
checkType(123) // get int
checkType("123") // get other
这篇关于将 Scala 类作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!