Skip to content
AgileLogics
5 min read

Classes

A class is a blueprint for objects that bundle data (fields) with behavior (methods).

class BankAccount(val owner: String, initialBalance: Double = 0):
  private var balance = initialBalance

  def deposit(amount: Double): Unit =
    require(amount > 0, "Deposit must be positive")
    balance += amount

  def currentBalance: Double = balance

  override def toString: String = s"$owner: $balance"

@main def accounts(): Unit =
  val account = BankAccount("Ada", 100)
  account.deposit(50)
  println(account.owner)
  println(account.currentBalance)
  println(account)
  try account.deposit(-5)
  catch case e: IllegalArgumentException => println(e.getMessage)
Ada
150.0
Ada: 150.0
requirement failed: Deposit must be positive
  • The constructor parameters go right after the class name.
  • val owner makes the parameter a public, read-only field. Without val (like initialBalance), it's only visible inside the class.
  • private members are hidden from outside code.
  • require checks a precondition and throws IllegalArgumentException if it fails.
  • In Scala 3, you create objects without new: BankAccount("Ada", 100).

Auxiliary constructors and validation

Default parameter values usually replace extra constructors. The class body runs when the object is created, so validation can go there:

class Temperature(val celsius: Double):
  require(celsius >= -273.15, s"Below absolute zero: $celsius")
  def fahrenheit: Double = celsius * 9 / 5 + 32

@main def temperatures(): Unit =
  println(Temperature(100).fahrenheit)
  try Temperature(-300)
  catch case e: IllegalArgumentException => println(e.getMessage)
212.0
requirement failed: Below absolute zero: -300.0

Classes vs case classes

Regular classes suit objects with identity and changing state — a bank account, a connection. For data — a point, an order, a user — Scala has case classes, the subject of the next lesson.