Search⌘ K
AI Features

Traits and Lists

Understand how Scala replaces Java interfaces with traits that can be mixed into classes or instances. Learn to work with Scala's immutable List, including creating lists, accessing elements, and appending items efficiently using Scala's apply method.

We'll cover the following...

Traits as Mixins

Scala does not have interfaces. But it has Traits instead, which is somewhat like a combined Interface and Abstract-base-class in Java. However, unlike anything in Java, Traits can be applied to classes or instances of classes and multiple Traits can be used.

Here’s an example using a Trait:

Scala
class SpaceShuttle(val name:String) {
def launch = println(name + " Take off!")
}
trait MoonLander {
def land = println("Landing!")
}
class MoonShuttle(name:String) extends SpaceShuttle(name) with MoonLander {
}
val apollo = new MoonShuttle("Apollo 27")
apollo.launch
apollo.land

A class can “extend” any number of Traits using the with ...