Classes and constructors
A class is a template for values that share behaviour. The parameter list of the class is its constructor, a parameter declared val or var becomes a field, and a member that is neither is visible inside the class and nowhere else. An instance is made with new.
A class and its state
Counter keeps a private var and offers two methods; the state is not reachable from outside, so the only way to change it is increment. Person declares its parameters as fields, one read-only and one writable:
classes.scala
class Counter(start: Int):
private var count = start
def increment(): Unit = count += 1
def value: Int = count
class Person(val name: String, var age: Int)
@main def classes(): Unit =
val counter = new Counter(2)
counter.increment()
counter.increment()
println(counter.value)
val ada = new Person("Ada", 36)
ada.age = 37
println(s"${ada.name} ${ada.age}")
scala-cli run --server=false classes.scala
4
Ada 37
The parameter start of Counter has no val, so it is a constructor argument and not a field: no counter.start compiles. Person keeps the two it declares, and age is assignable because it is a var.
The primary constructor
The body of the class runs at construction, which is where a check belongs. A require that fails throws an IllegalArgumentException before the object exists, so no instance is ever in the invalid state:
constructors.scala
class Temperature(val celsius: Double):
require(celsius >= -273.15, "below absolute zero")
def fahrenheit: Double = celsius * 9 / 5 + 32
override def toString: String = f"$celsius%.1f C"
class Point(val x: Int, val y: Int):
def this(value: Int) = this(value, value)
@main def constructors(): Unit =
val boiling = new Temperature(100)
println(boiling.fahrenheit)
println(boiling)
val origin = new Point(3)
println(s"${origin.x},${origin.y}")
scala-cli run --server=false constructors.scala
212.0
100.0 C
3,3
Temperature(-300) stops at the require with the message the class wrote. toString is overridden because a temperature printed as a memory address tells a reader nothing, and the format string of the strings lesson writes the one decimal.
An auxiliary constructor
def this(value: Int) = this(value, value) is a second constructor: it must call the primary one as its first action, so every instance still passes through the primary and its checks. An auxiliary constructor is for a convenience the primary cannot express — here a square point from one number — and a factory method on a companion object is usually the better place for it, which the next lesson shows.
Related
- Objects and companions: the factory that replaces new.
- Opaque types: a class-free way to make a new type.
- Equality: the method a class has to write for ==.
- Java: classes and constructors in the language Scala shares the platform with.
Article author: Arthur Isaev