简体   繁体   中英

Scala - Passing Trait type as method parameter

In java, we can have a method that takes Class as a parameter, for example :

void someMethod(Class className)
{
   System.out.println(className);
}

similarly, instead of Class, is there a way in scala to take Trait as a parameter ?

If you could do that, how would you use it?

A Scala trait is compiled into an interface and a corresponding class. You can pass the interface into a method (since interfaces are a kind of 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. However, you can pass a Class that implements your Trait into a method. I'm not aware of a way to pass a Trait directly, due to the split into the underlying Java class and interface.

See also this answer and this one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM