Chuyển đến nội dung

Bài 16 · Classes, Traits and Objects

Singleton Objects and Companions

Learn Scala's singleton object, companion objects for static-like members and factories, apply and unapply, private constructors, and how objects replace Java static.

Java has static members: fields and methods that belong to the class rather than to an instance. Scala has no static keyword. Instead it has objects: a declaration that creates exactly one instance of itself, a singleton. An object with the same name as a class and in the same file is that class's companion, and it holds everything that would be static in Java: constants, factory methods and helpers. This lesson explains both. Scala is read-only here; runnable Java and Kotlin examples show the same patterns.

A singleton object

SCALA
object Config:
  val appName = "ShopApp"
  val maxItems = 100
  def describe: String = s"$appName (max $maxItems)"

println(Config.appName)     // ShopApp
println(Config.describe)    // ShopApp (max 100)

object Config defines a type and its only instance in one go. You never write new Config. The object is created lazily, the first time you access it, and the creation is thread-safe. Objects are ideal for:

  • constants and configuration,
  • utility functions (like Math in Java),
  • entry points (an object with a main),
  • global registries, used with care.

Kotlin's object is the same idea, runnable here:

Kotlin A singleton (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In Java you would write a class with private constructor and static members, or an enum with one value.

Companion objects

A companion object has the same name as a class and is defined in the same source file. The class and its companion can see each other's private members.

SCALA
class Circle(val radius: Double):
  def area: Double = Circle.Pi * radius * radius

object Circle:
  val Pi = 3.14159
  def unit: Circle = Circle(1.0)

Circle.Pi          // 3.14159
Circle.unit.area   // 3.14159
Circle(2.0).area   // 12.56636

What lives where:

In the class In the companion
Per-instance data and methods Constants, counters, factories, helpers
Needs an instance (c.area) Called on the name (Circle.unit)

This is how Scala replaces static: it is not special syntax, it is an ordinary object with the right name.

apply: factory methods

A method named apply on an object lets you call the object like a function. This is the reason List(1, 2, 3) works: it is List.apply(1, 2, 3).

SCALA
class Temperature private (val celsius: Double):
  def fahrenheit: Double = celsius * 9 / 5 + 32

object Temperature:
  def apply(celsius: Double): Temperature =
    require(celsius >= -273.15, "below absolute zero")
    new Temperature(celsius)

  def fromFahrenheit(f: Double): Temperature = apply((f - 32) * 5 / 9)

Temperature(100).fahrenheit            // 212.0
Temperature.fromFahrenheit(32).celsius // 0.0
// new Temperature(5)                  // error: constructor is private

Here the constructor is private, so callers must go through the companion. That lets you validate, cache or choose a subclass before returning, which a bare constructor cannot do. Because Scala 3 creator applications treat Temperature(100) like a constructor call even if the class has no apply, the style is consistent from the caller's side.

The same factory idea in Java, runnable:

Java Static factory with private constructor (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

unapply: extractors

unapply is the reverse of apply. It makes an object usable as a pattern:

SCALA
object Email:
  def unapply(text: String): Option[(String, String)] =
    text.split("@") match
      case Array(user, domain) => Some((user, domain))
      case _ => None

"[email protected]" match
  case Email(user, domain) => println(s"$user at $domain")
  case _ => println("not an email")
// ada at example.com

Case classes get apply and unapply generated automatically, which is why case Circle(r) patterns work. Writing your own unapply is useful for parsing.

Counting instances: a state example

Companions can hold shared state. Use it sparingly, because global mutable state is hard to test:

SCALA
class Ticket private (val id: Int)

object Ticket:
  private var next = 1
  def create(): Ticket =
    val t = Ticket(next)
    next += 1
    t

Ticket.create().id   // 1
Ticket.create().id   // 2

The companion can call the private constructor, and nothing else can. Note that next is not thread-safe; real code would use an AtomicInteger.

Objects as entry points and modules

Objects also group related functions, like a module:

SCALA
object StringUtils:
  def isPalindrome(s: String): Boolean =
    val clean = s.toLowerCase.filter(_.isLetter)
    clean == clean.reverse

import StringUtils.isPalindrome
isPalindrome("A man, a plan, a canal: Panama")   // true

Because there is no static, you also see object in libraries as namespaces: scala.math, scala.util.Random, java.lang.Math accessed as Math.max.

Case objects and enums (preview)

A case object is a singleton with a nice toString and pattern-matching support. Scala 3 mostly uses enum instead, which you will meet in the next chapter. For now know that object can also extend a class or trait:

SCALA
trait Greeter:
  def greet(name: String): String

object FriendlyGreeter extends Greeter:
  def greet(name: String): String = s"Hey $name!"

Common mistakes

  • Putting the companion in a different file, so private access fails. Keep both in one file.
  • Using an object for everything. Reserve it for single shared things; use classes for data with several instances.
  • Hiding mutable state in objects, which makes tests depend on each other.
  • Looking for a static keyword. It does not exist.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What replaces Java's static members in Scala?

    Scala puts constants, helpers and factories in object declarations, typically a companion of the class.
  2. 2. What makes an object the companion of a class?

    A companion has the same name as the class and sits in the same source file, giving it access to private members.
  3. 3. What does a method named apply allow?

    Foo(1) is shorthand for Foo.apply(1), which is how List(1, 2, 3) is built.
  4. 4. What is unapply used for?

    unapply is an extractor: it decomposes a value so it can be matched with case Name(a, b).

Summary

  • object declares a lazily created, thread-safe singleton.
  • A companion object (same name, same file) holds the class's static-like members and factories.
  • apply allows Name(args) calls; a private constructor plus apply gives you controlled creation.
  • unapply creates extractors for pattern matching.
  • Keep objects free of hidden mutable state where possible.

Next: Inheritance and Abstract Classes

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.