FP Module 2 - 101 Scala


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content


Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods.

Like in Java 8, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods.

In contrast to classes, traits may not have constructor parameters. Here is an example:

trait Similarity {
  def isSimilar(x: Any): Boolean
  def isNotSimilar(x: Any): Boolean = !isSimilar(x)

This trait consists of two methods isSimilar and isNotSimilar. While isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), method isNotSimilar defines a concrete implementation.

Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. The behavior for isNotSimilar gets inherited directly from the trait. Traits are typically integrated into a class (or other traits) with a mixin class composition

class Point(xc: Int, yc: Int) extends Similarity {
  var x: Int = xc
  var y: Int = yc
  def isSimilar(obj: Any) =
    obj.isInstanceOf[Point] &&
    obj.asInstanceOf[Point].x == x

object TraitsTest extends App {
  val p1 = new Point(2, 3)
  val p2 = new Point(2, 4)
  val p3 = new Point(3, 3)

Here is the output of the program:



As opposed to languages that only support single inheritance, Scala has a more general notion of class reuse :

  • The first parent is called the “superclass” and is defined with keyword extends
  • The second (and every others) are called “mixin”
trait A {  def a }
trait B { def b }
trait C { def c }

class D extends A with B with C

abstract class Animal { def name: String }
trait Vegetarien {
    def eat() = println("No T-bone steak for me")
class Rabbit extends Animal with Mammal with Vegetarian
a Quadriped should have 4 legs
a BiPed should have 2 legs
A Cow should have 2 legs
A Cow should Meuh! Meuh!
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content