[英]Scala - Passing Trait type as method parameter
In java, we can have a method that takes Class as a parameter, for example : 在java中,我们可以有一个将Class作为参数的方法,例如:
void someMethod(Class className)
{
System.out.println(className);
}
similarly, instead of Class, is there a way in scala to take Trait as a parameter ? 类似地,在Scala中有没有一种方法可以将Trait作为参数而不是Class?
If you could do that, how would you use it? 如果可以做到,您将如何使用它?
A Scala trait is compiled into an interface and a corresponding class. Scala特征被编译为接口和相应的类。 You can pass the interface into a method (since interfaces are a kind of Class): 您可以将接口传递给方法(因为接口是一种Class):
scala> trait Foo
scala> val c: Class = classOf[Foo]
a: Class[Foo] = interface Foo
scala> def someMethod(c: Class[_]) = c.getName
scala> someMethod(a)
res1: String = Foo
The class part is compiled into a hidden Foo$class
classfile. 类部分被编译成一个隐藏的Foo$class
类文件。 However, you can pass a Class that implements your Trait into a method. 但是,您可以将实现您的Trait的Class传递给方法。 I'm not aware of a way to pass a Trait directly, due to the split into the underlying Java class and interface. 由于拆分为基础Java类和接口,我不知道直接传递特性的方法。
See also this answer and this one 另请参阅此答案和此 答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.