0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Sealed Traits

Closed hierarchies.

What Is a Trait?

A trait is like an interface: it declares a common type that other classes can extend.

Traits let you group related types under one umbrella so they can be used interchangeably.

A Basic Trait

Declare a trait with trait, then have classes or objects extends it.

trait Shape
case class Circle(r: Double) extends Shape
case class Square(side: Double) extends Shape
object Main {
  def main(args: Array[String]): Unit = {
    val s: Shape = Circle(2.0)
    println(s)
  }
}

All lessons in this course

  1. Case Classes
  2. Sealed Traits
  3. Algebraic Data Types
  4. Exhaustive Matching
← Back to Scala for Backend Engineering & Functional Programming