Objects and companions

An object is a class with one instance, created the first time it is used. It is where a Scala program puts a constant, a factory and the methods that belong to a type but not to one of its values. When the object has the same name as a class and lives in the same file, the two are companions: each can see the private members of the other.

A singleton

Registry is one object for the whole program. Its map is private, and the two methods are the only way in, which is the same encapsulation a class has with one instance:

singleton.scala

object Registry: private var entries: Map[String, Int] = Map.empty def register(name: String, value: Int): Unit = entries = entries.updated(name, value) def get(name: String): Option[Int] = entries.get(name) @main def registryMain(): Unit = Registry.register("a", 1) Registry.register("b", 2) println(Registry.get("a")) println(Registry.get("c"))

scala-cli run --server=false singleton.scala

Some(1)
None

get answers an Option, so a missing name is a value and not an exception. An object with mutable state is a global, and the course uses one only where the program really has a single instance of something: a registry, a pool, a configuration.

The companion object

The object beside the class is where a value is made. apply lets the call site write User("Ada") without new, an overload gives the admin form, and a val holds the one guest:

companion.scala

class User(val name: String, val admin: Boolean) object User: def apply(name: String, admin: Boolean): User = new User(name, admin) def apply(name: String): User = apply(name, admin = false) def admin(name: String): User = apply(name, admin = true) val guest: User = apply("guest") def unapply(user: User): Option[(String, Boolean)] = Some((user.name, user.admin)) @main def companion(): Unit = val ada = User("Ada") println(ada.name) println(ada.admin) println(User.admin("root").admin) println(User.guest.name) ada match case User(name, admin) => println(s"$name $admin")

scala-cli run --server=false companion.scala

Ada
false
true
guest
Ada false

The companion sees the private members of the class and the class sees the private members of the companion, which is how a factory enforces an invariant the constructor cannot check on its own. A companion that declares apply gets the call syntax for free; one that declares unapply gets the pattern.

apply and unapply

apply turns an object into something that can be called, and unapply turns it into a pattern that can take a value apart. The last two lines of the program are the pair: User(name, admin) in a case is User.unapply answering an Option of what it found. The extractors lesson writes ones that are not a companion.

Related

Article author: Arthur Isaev