typestar

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

  1. trait Shape leaves name and area abstract, then defines describe in terms of them.
  2. case class Circle and case class Rect supply the two abstract members and inherit the rest.
  3. val shapes: List[Shape] holds both kinds, and shapes.map(_.describe) reaches the right area for each.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Traits & extensions, step 22 of 27 in Language basics.

← Previous Next →

Traits in other languages