Using Traits from Java

You’ll run into a few idiosyncrasies when using traits from Java—nothing impossible, but there are some rough edges we have to work around, so let’s walk through this section in smaller steps.

Scala traits with no method implementation are simple interfaces at the bytecode level. Scala doesn’t support the interface keyword. If you want to create interfaces in Scala, you’d create traits with no implementation in them. Here’s an example of a Scala trait, which in effect is simply an interface:

Intermixing/Writable.scala
 
trait​ Writable {
 
def​ write(message: ​String​) : ​Unit
 
}

The trait has one abstract method that should be implemented by any class that mixes in this trait. On the Java side, Writable is seen like ...

Get Pragmatic Scala now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.