Scala Classes
A class is a blueprint for objects that bundle data (fields) and behaviour (methods). Scala classes are compact: the constructor parameters go right after the class name, and the class body is the constructor.
A first class
class BankAccount(val owner: String, initial: Double):
private var balance = initial
def deposit(amount: Double): Unit =
require(amount > 0, "deposit must be positive")
balance += amount
def withdraw(amount: Double): Boolean =
if amount <= balance then
balance -= amount
true
else false
def current: Double = balance
@main def run(): Unit =
val acc = BankAccount("Rosa", 100)
acc.deposit(50)
println(acc.withdraw(30))
println(acc.withdraw(500))
println(s"${acc.owner} has ${acc.current}")true
false
Rosa has 120.0
val ownerbecomes a public, read-only field.initialhas noval, so it is only a constructor parameter, visible inside the class body.private var balanceis hidden from the outside; callers must go throughdepositandwithdraw.- In Scala 3 you can create an instance without
new:BankAccount("Rosa", 100).
Constructor parameter kinds
| Declaration | Field? | Readable outside? | Reassignable? |
|---|---|---|---|
class A(x: Int) |
only if used in methods (private) | no | no |
class A(val x: Int) |
yes | yes | no |
class A(var x: Int) |
yes | yes | yes |
class A(private val x: Int) |
yes | no | no |
Auxiliary constructors and default values
Default parameter values usually make extra constructors unnecessary, but you can still define them with def this(...). Each must call another constructor first.
class Rectangle(val width: Double, val height: Double = 1.0):
def this(side: Int) = this(side.toDouble, side.toDouble)
def area: Double = width * height
override def toString = s"Rectangle($width x $height)"
@main def run(): Unit =
println(Rectangle(3.0, 2.0))
println(Rectangle(5.0))
println(Rectangle(4))
println(Rectangle(4).area)Rectangle(3.0 x 2.0)
Rectangle(5.0 x 1.0)
Rectangle(4.0 x 4.0)
16.0
Overriding toString controls how the object prints; otherwise you would see something like Rectangle@6d06d69c.
Inheritance
A class can extend one other class. Methods marked override replace the parent's version. A class that should not be instantiated itself is marked abstract.
abstract class Shape(val name: String):
def area: Double
def describe: String = f"$name with area $area%.2f"
class Circle(r: Double) extends Shape("circle"):
def area: Double = math.Pi * r * r
class Square(side: Double) extends Shape("square"):
def area: Double = side * side
override def describe: String = s"a perfect ${super.describe}"
@main def run(): Unit =
val shapes: List[Shape] = List(Circle(1), Square(3))
shapes.foreach(s => println(s.describe))circle with area 3.14
a perfect square with area 9.00
The list has type List[Shape], but each element runs its own area — this is polymorphism.
Note: Scala 3 classes are open for extension by default, but the compiler warns when you extend a class from another file unless it is marked
open. Usefinal classto forbid subclasses entirely.
Access modifiers
| Modifier | Visible to |
|---|---|
| (none) | everyone (public is the default) |
private |
this class and its companion object |
protected |
this class and its subclasses |
private[pkg] |
everything inside package pkg |
Initialisation order
The class body runs top to bottom when the object is created. Put validation (require) early so invalid objects are never built.
class Temperature(val celsius: Double):
require(celsius >= -273.15, s"$celsius is below absolute zero")
println(s"created $celsius°C")
val fahrenheit: Double = celsius * 9 / 5 + 32
@main def run(): Unit =
val t = Temperature(25)
println(t.fahrenheit)
try Temperature(-300)
catch case e: IllegalArgumentException => println(e.getMessage)created 25.0°C
77.0
requirement failed: -300.0 is below absolute zero
Equality of plain classes
Plain classes compare by reference: two objects with the same field values are still different. If you want value-based equality (and a nice toString, copy and pattern matching for free), use a case class — the topic of an upcoming chapter.
class P(val x: Int)
P(1) == P(1) // false
case class Q(x: Int)
Q(1) == Q(1) // trueTest yourself
In class User(val name: String, age: Int), which parameter is accessible as user.name from outside?
- Only
age - Only
name - Both
- Neither
Which keyword prevents a class from being extended?
sealedfinalprivatestatic
What must a method in a subclass use to replace a concrete parent method?
newoverridesupervirtual