Scala Objects & Companion Objects
An object defines a class and its single instance in one step. Objects replace Java's static members: they hold utility methods, constants, factories and application entry points. When an object has the same name as a class in the same file, it is that class's companion.
Singleton objects
object MathUtils:
val GoldenRatio = 1.618
def square(x: Double): Double = x * x
def clamp(x: Int, lo: Int, hi: Int): Int = x.max(lo).min(hi)
@main def run(): Unit =
println(MathUtils.square(1.5))
println(MathUtils.clamp(42, 0, 10))
println(MathUtils.GoldenRatio)2.25
10
1.618
The object is created lazily, the first time it is used, and there is only ever one instance.
Objects with state
Because there is only one instance, state inside an object is shared by everyone who uses it. That makes objects handy for counters and registries — but use mutable state sparingly.
object IdGenerator:
private var last = 0
def next(): Int =
last += 1
last
@main def run(): Unit =
println(IdGenerator.next())
println(IdGenerator.next())
println(IdGenerator.next())1
2
3
Companion objects
A class and an object with the same name, defined in the same file, are companions. They can access each other's private members. The companion is the natural place for factory methods and constants that belong to the type rather than to an individual instance.
class Temperature private (val kelvin: Double):
def celsius: Double = kelvin - 273.15
override def toString = f"$celsius%.1f°C"
object Temperature:
val AbsoluteZero = Temperature(0)
def fromCelsius(c: Double): Temperature = new Temperature(c + 273.15)
def fromFahrenheit(f: Double): Temperature = fromCelsius((f - 32) * 5 / 9)
private def apply(k: Double): Temperature = new Temperature(k)
@main def run(): Unit =
println(Temperature.fromCelsius(21.5))
println(Temperature.fromFahrenheit(212))
println(Temperature.AbsoluteZero)21.5°C
100.0°C
-273.2°C
The constructor is private, so outside code must use the named factory methods — a clear API that says which unit you are passing.
The apply method
When you write Name(args), Scala calls Name.apply(args). Defining apply in a companion object lets you control how instances are created — for example to validate or normalise input.
class Email private (val address: String):
override def toString = s"<$address>"
object Email:
def apply(raw: String): Option[Email] =
val cleaned = raw.trim.toLowerCase
if cleaned.contains("@") then Some(new Email(cleaned)) else None
@main def run(): Unit =
println(Email(" Ana@Example.COM "))
println(Email("not-an-email"))Some(<ana@example.com>)
None
Objects as entry points and implementations
An object can extend a trait, which is a neat way to provide a single implementation. And an object with a main method is a program entry point.
trait Greeter:
def greet(name: String): String
object FriendlyGreeter extends Greeter:
def greet(name: String) = s"Hey $name, great to see you!"
object Main:
def main(args: Array[String]): Unit =
val g: Greeter = FriendlyGreeter
println(g.greet("Theo"))Hey Theo, great to see you!
Object vs. class
class |
object |
|
|---|---|---|
| Instances | as many as you create | exactly one |
| Constructor parameters | yes | no |
| Created | with Name(...) / new |
automatically, on first use |
| Typical use | domain entities, services with state per instance | utilities, constants, factories, entry points |
Tip: In Scala 3 you can also put simple helper methods at the top level of a file instead of wrapping them in an object. Use an object when the members belong together under a clear name, like
MathUtils.square.
Test yourself
How many instances of an object exist?
- None
- Exactly one
- One per thread
- As many as you create with
new
What makes an object the companion of a class?
- It extends the class
- It has the same name and is in the same file
- It is marked
companion - It is nested inside the class
What does Email("x@y.z") call when Email has a companion with an apply method?
- The class constructor directly
Email.apply("x@y.z")Email.new("x@y.z")Email.create("x@y.z")