2

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 ?

Mahendra
  • 21
  • 1
  • 3

1 Answers1

4

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

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146