5.2. Calling a Method on a Superclass

Problem

To keep your code DRY (“Don’t Repeat Yourself”), you want to invoke a method that’s already defined in a parent class or trait.

Solution

In the basic use case, the syntax to invoke a method in an immediate parent class is the same as Java: Use super to refer to the parent class, and then provide the method name. The following Android method (written in Scala) demonstrates how to call a method named onCreate that’s defined in the Activity parent class:

class WelcomeActivity extends Activity {
  override def onCreate(bundle: Bundle) {
    super.onCreate(bundle)
    // more code here ...
  }
}

As with Java, you can call multiple superclass methods if necessary:

class FourLeggedAnimal {
  def walk { println("I'm walking") }
  def run { println("I'm running") }
}

class Dog extends FourLeggedAnimal {
  def walkThenRun {
    super.walk
    super.run
  }
}

Running this code in the Scala REPL yields:

scala> val suka = new Dog
suka: Dog = Dog@239bf795

scala> suka.walkThenRun
I'm walking
I'm running

Controlling which trait you call a method from

If your class inherits from multiple traits, and those traits implement the same method, you can select not only a method name, but also a trait name when invoking a method using super. For instance, given this class hierarchy:

trait Human {
  def hello = "the Human trait"
}

trait Mother extends Human {
  override def hello = "Mother"
}

trait Father extends Human {
  override def hello = "Father"
}

The following code shows different ways to invoke ...

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.