typestar

Objects and companions in Scala

An object is a namespace with one instance; a companion is where constructors go.

// A plain object is a namespace: one instance, no constructor.
object Temperature:
  val absoluteZero: Double = -273.15
  def toFahrenheit(celsius: Double): Double = celsius * 9 / 5 + 32

// A companion object shares its name with a class and can reach the
// class's private parts, which makes it the place for constructors.
class Passcode private (val digits: String):
  def masked: String = "*" * digits.length

object Passcode:
  // A smart constructor validates first and may refuse to build.
  def apply(raw: String): Option[Passcode] =
    if raw.length == 6 && raw.forall(_.isDigit) then Some(new Passcode(raw))
    else None

val freezing: Double = Temperature.toFahrenheit(0.0)
val rejected: Option[Passcode] = Passcode("12ab56")
val accepted: Option[String] = Passcode("314159").map(_.masked)

How it works

  1. object Temperature groups absoluteZero and toFahrenheit with nothing to instantiate.
  2. class Passcode private hides its constructor from every caller except its companion.
  3. def apply(raw: String) checks the digits first and returns None rather than building a bad value.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
786
Tokens
135
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 108 seconds.

Type this snippet

Step 3 of 3 in Traits & extensions, step 24 of 27 in Language basics.

← Previous Next →

Objects and companions in other languages