Scala Easy · Lesson 1 · On the house

Traits

trait, extends, with, abstract members, mixins. Lesson 1 is free — on the house.

Lessons · Scala Easy · Lesson 1 of 10 · On the house

Traits

trait, extends, with, abstract members, mixins.

Illustration for Scala
Lesson 1 is on the house.

A trait is a reusable interface-plus-behavior unit. Declare it with trait Named { def name: String }. Traits can hold abstract members (no body) and concrete methods.

A class mixes in a trait with extends: class Person(val name: String) extends Named. Mix additional traits with with: extends Named with Greetable.

When the first parent is a trait (no class superclass), write extends TraitA with TraitB. Order matters for linearization when methods override each other — later mixins win for the same method name unless you use super.

Traits may take constructor parameters in modern Scala 3; in classic Scala 2 style (this track's stills), keep trait fields as abstract def/val members the class supplies.

Misses: writing interface / protocol keywords, using implements like Java, or treating a trait as a singleton object you never extend.

traits

trait Named {
  def name: String
}

trait Greetable extends Named {
  def greet(): String = s"hi $name"
}

class Person(val name: String) extends Greetable

object TraitsDemo {
  def main(args: Array[String]): Unit = {
    val ada = new Person("Ada")
    println(ada.greet())
  }
}
Match this when you type.

Quiz

How do you declare a reusable Scala mixin type?

Quiz

How do you mix a second trait after the first?

Quiz

Can a trait provide a concrete method body?

Quiz

What does class Person(val name: String) extends Greetable supply?

Check

Match the still for: Traits.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.