🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Classes

A class is a blueprint for values that group data together. One class can make many values, and each value holds its own data.

Create a value and read its fields

The class line lists two fields. The main lines make one Dog value and print both fields.

class Dog(val name: String, val age: Int)

@main def main(): Unit =
  val rex = Dog("Rex", 3)
  println(rex.name)
  println(rex.age)

One class makes many separate values

Two Dog values come from the same class. Each one keeps its own name and age.

class Dog(val name: String, val age: Int)

@main def main(): Unit =
  val bella = Dog("Bella", 5)
  val max = Dog("Max", 2)
  println(bella.name)
  println(max.name)
  println(bella.age + max.age)

Many values fit in one list

A list can hold Dog values made by the same class. The map step reads the name field of each dog.

class Dog(val name: String, val age: Int)

@main def main(): Unit =
  val dogs = List(Dog("Rex", 3), Dog("Bella", 5), Dog("Max", 2))
  println(dogs.length)
  println(dogs.map(d => d.name).mkString(", "))

Example

class Dog(val name: String, val age: Int)

@main def main(): Unit =
  val rex = Dog("Rex", 3)
  val bella = Dog("Bella", 5)
  println(s"${rex.name}: ${rex.age}")
  println(s"${bella.name}: ${bella.age}")
  val older = if bella.age > rex.age then bella.name else rex.name
  println(older)

Key points

  • Class: a plan for making values that hold related data together.
  • Fields: the pieces of data a class value holds, such as a name and an age.
  • Constructor parameters: the field list written in parentheses after the class name.
  • Create: write the class name with values in parentheses, like Dog("Rex", 3), to make a value.
  • Dot: read a field by writing the value, a dot, and the field name, like rex.age.
  • Reuse: one class can make many values, and each value keeps its own field values.

In this example, the Dog class groups a name and an age into one value. The program makes two dogs and prints each name with its age. The if step compares the two age fields and stores the older dog's name, which prints last.

Note

Scala 3 needs no new word before the class name when a value is created.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

Which line creates a Dog value and stores it in a val?