Home > Article >

Article: Scala vs Java - Scala Traits are Like Interfaces in Java 8

For Java developers, Scala traits share many of the characteristics of interfaces in Java 8.

Published

scala trait
Author: Mensah Alkebu-Lan

Pre-Requisites #

  • Some familiarity with interfaces in Java
  • Some familiarity with abstract methods and abstract classes
  • Some familiarity with the concept of multiple inheritance

Table of Contents #

Similar to Interfaces in Java #

For Java developers, traits in Scala share many of the characteristics of interfaces in Java 8. Minimally, a trait requires the trait keyword and an identifier (or name).

Just as in the Java language where an interface can extend another interface, a trait in Scala can extend another trait. Classes and objects can extend traits. You can use the extends keyword to extend a trait. Then, using the with keyword, you are able to inherit two traits, and, with multiple with keywords you are able to inherit additional traits. In other words, the Scala programming language supports multiple inheritance of traits. Java developers are sure to notice Scala developers do not use the implements keyword.

Similar to abstract classes in Java, traits can have abstract and non-abstract methods as members. Very often, your trait will include abstract methods. For example, a trait could be defined as such:

trait GroupMappingServiceProvider {

def getGroups(userName : String) : Set[String]
}

Extending the Behavior of Classes and Objects #

Classes extending a trait or having the trait in its inheritance hierarchy can implement abstract members (i.e. methods) defined in the trait by using the override keyword. And so, if we wanted to implement the method getGroups from the trait above, we could do the following:

...
class ShellBasedGroupsMappingProvider extends GroupMappingServiceProvider {

override def getGroups(username: String): Set[String] = {
val userGroups = getUnixGroups(username)
userGroups
}

private def getUnixGroups(username: String): Set[String] = {
val cmdSeq = Seq("bash", "-c", "id -Gn " + username)

Utils.executeAndGetOutput(cmdSeq).stripLineEnd.split(" ").toSet
}
}

If you look at the method signature in both the trait and the extending class, you may notice they are the same.

References #

  1. Scala | Traits - GeeksforGeeks.