(11) Traits
About
:octocat: GitHub: All of the example code: repo (link)
:page_facing_up: blog link: https://purrgramming.life/cs/programming/fp/ :star:
Motivation
In Java, as well as in Scala, a class can only have one superclass.
But what if a class has several natural supertypes to which it conforms or from which it wants to inherit code? Here, you could use traits.
Classes, objects and traits can inherit from at most one class but many arbitrary traits.
Scala Trait vs Java Interface
Traits resemble interfaces in Java but are more powerful because they have parameters and contain fields and concrete methods.
Similarly to Java, in Scala, it is possible to
- have only one superclass
- can extend multiple traits (interfaces in Java)
Usage
Traits are similar to interfaces in Java and are created using trait keywords.
But what if a class has several natural supertypes to which it conforms or
from which it wants to inherit code?
Here, you could use traits
.
A trait is declared like an abstract class, just with a trait instead of
abstract class
// Creating a super class
abstract class Shapes {
def draw() = println("Draw the shape")
// Overload
def draw(id: Int) = println(s"Draw the shape (Id: $id)")
}
trait MathShape {
def size: Int
}
// Creating a subclass
class Rectangle extends Shapes {
def size = println("length (L) * width (W) ")
}
// Creating a subclass
class Circle extends Shapes {
// Overriding
override def draw() = println("Draw the Circle")
// Override, Overload
override def draw(id: Int) = println(s"Draw the Circle (Id: $id)")
def size = println("pi * radius^2 ")
}
val rectangle = new Rectangle
rectangle.draw()
rectangle.draw(0)
rectangle.size
val circle = new Circle
circle.draw()
circle.draw(1)
circle.size
Abstract Class vs Trait
image source: https://drek4537l1klr.cloudfront.net/sfregola/v-2/Figures/11_02.png
Key | Trait | Abstract Class |
---|---|---|
Multiple inheritance | Trait supports multiple inheritances. | Abstract Class supports single inheritance only. |
Instance | Trait can be added to an object instance. | Abstract class cannot be added to an object instance. |
Constructor parameters | Trait cannot have parameters in its constructors. | Abstract class can have parameterised constructor. |
Interoperability | Traits are interoperable with java if they don’t implement any. | Abstract classes are interoperable with java without any restriction. |
Stackability | Traits are stackable and are dynamically bound. | Abstract classes are not stackable and are statically bound. |