Traits in Scala
A trait fixes what every shape must answer and writes the shared part once.
// A trait can leave members abstract and still define others in terms
// of them, so every implementer inherits describe for free.
trait Shape:
def name: String
def area: Double
def describe: String = f"$name covers $area%.2f"
// A case class supplies the abstract members and nothing more.
case class Circle(radius: Double) extends Shape:
def name: String = "circle"
def area: Double = math.Pi * radius * radius
case class Rect(width: Double, height: Double) extends Shape:
def name: String = "rect"
def area: Double = width * height
// Typing the List as the trait lets both shapes live in it, and each
// call to describe reaches the right area at run time.
val shapes: List[Shape] = List(Circle(1.5), Rect(2.0, 3.0), Circle(0.5))
val report: List[String] = shapes.map(_.describe)
How it works
trait Shapeleavesnameandareaabstract, then definesdescribein terms of them.case class Circleandcase class Rectsupply the two abstract members and inherit the rest.val shapes: List[Shape]holds both kinds, andshapes.map(_.describe)reaches the rightareafor each.
Keywords and builtins used here
CircleDoubleListPiRectShapeStringareacaseclassdefdescribeextendsnametraitval
The run, in numbers
- Lines
- 20
- Characters to type
- 787
- Tokens
- 130
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 104 seconds.
Step 1 of 3 in Traits & extensions, step 22 of 27 in Language basics.