8.1. Using a Trait as an Interface

Problem

You’re used to creating interfaces in other languages like Java and want to create something like that in Scala.

Solution

You can use a trait just like a Java interface. As with interfaces, just declare the methods in your trait that you want extending classes to implement:

trait BaseSoundPlayer {
  def play
  def close
  def pause
  def stop
  def resume
}

If the methods don’t take any argument, you only need to declare the names of the methods after the def keyword, as shown. If a method should require parameters, list them as usual:

trait Dog {
  def speak(whatToSay: String)
  def wagTail(enabled: Boolean)
}

When a class extends a trait, it uses the extends and with keywords. When extending one trait, use extends:

class Mp3SoundPlayer extends BaseSoundPlayer { ...

When extending a class and one or more traits, use extends for the class, and with for subsequent traits:

class Foo extends BaseClass with Trait1 with Trait2 { ...

When a class extends multiple traits, use extends for the first trait, and with for subsequent traits:

class Foo extends Trait1 with Trait2 with Trait3 with Trait4 { ...

Unless the class implementing a trait is abstract, it must implement all of the abstract trait methods:

class Mp3SoundPlayer extends BaseSoundPlayer {
  def play   { // code here ... }
  def close  { // code here ... }
  def pause  { // code here ... }
  def stop   { // code here ... }
  def resume { // code here ... }
}

If a class extends a trait but does not implement the abstract methods ...

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.