September 2018
Intermediate to advanced
398 pages
9h 43m
English
A trait is similar to an abstract class: it can declare several abstract or concrete members and can be extended. It cannot be instantiated. The difference is that a given class can only extend one abstract class, however, it can mixin one to many traits. Also, a trait cannot have constructor arguments.
For instance, we can declare several traits, each declaring different abstract methods, and mixin them all in the Rectangle class:
trait Description { def description: String}trait Coordinates extends Description { def x: Int def y: Int def description: String = "Coordinates (" + x + ", " + y + ")"}trait Area { def area: Double}class Rectangle(val x: Int, val y: Int, val width: Int, val height: Int) extends Coordinates with Description ...
Read now
Unlock full access