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:

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.