O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required