8.9. Extending a Java Interface Like a Trait

Problem

You want to implement a Java interface in a Scala application.

Solution

In your Scala application, use the extends and with keywords to implement your Java interfaces, just as though they were Scala traits.

Given these three Java interfaces:

// java
public interface Animal {
  public void speak();
}

public interface Wagging {
  public void wag();
}

public interface Running {
  public void run();
}

you can create a Dog class in Scala with the usual extends and with keywords, just as though you were using traits:

// scala
class Dog extends Animal with Wagging with Running {
  def speak { println("Woof") }
  def wag { println("Tail is wagging!") }
  def run { println("I'm running!") }
}

The difference is that Java interfaces don’t implement behavior, so if you’re defining a class that extends a Java interface, you’ll need to implement the methods, or declare the class abstract.

Get Scala Cookbook 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.