Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a PR from a developer who was trying to implement a data parser for a financial transaction system. They had created a Transaction case class and, in an attempt to keep everything "encapsulated," they put the parsing logic—the code that took a raw CSV string and turned it into a Transaction object—inside the class itself. The problem was that to call the parse method, they first had to instantiate a dummy Transaction object. It felt clunky and logically backward: why do I need a Transaction just to create a Transaction?

This is the exact friction point that companion objects are designed to solve. Since Scala doesn't have the static keyword you'll find in Java or C#, it uses companion objects to house members that belong to the class as a whole, rather than to any specific instance of that class.

Bridging the Gap Between Class and Object

A companion object is simply an object with the exact same name as a class, defined in the same source file. The "magic" happens in the relationship between the two. While they are technically distinct types, they share a special privilege: they can access each other's private members.

case class User(name: String, email: String, private var loginCount: Int)

object User {
  def incrementLogin(user: User): Unit = {
    // I can access loginCount even though it's private in the class
    user.loginCount += 1
    println(s"User ${user.name} has logged in ${user.loginCount} times.")
  }
}

In this example, User is the blueprint for creating users, but User (the object) is a singleton that provides utility logic related to users. I often use this pattern to keep the class definition clean, focusing only on the data and instance-specific behavior, while moving the "managerial" logic into the companion object.

The Power of the apply Method

If you've been using case classes, you've already been using companion objects without realizing it. When you write val u = User("Alice", "a@example.com", 0), you aren't actually calling a constructor in the traditional sense. You're calling a method named apply on the User companion object.

By defining your own apply method, you can create sophisticated factory patterns. You can add validation, return different subtypes of the class, or handle complex initialization logic before the object is ever created. It's a way to decouple the creation of an object from the definition of the object.

case class DatabaseConfig(url: String, timeout: Int)

object DatabaseConfig {
  // A custom factory method to provide a default config
  def apply(url: String): DatabaseConfig = {
    new DatabaseConfig(url, 30) // Default timeout of 30 seconds
  }

  def fromEnv(): DatabaseConfig = {
    val url = sys.env.getOrElse("DB_URL", "localhost:5432")
    val timeout = sys.env.getOrElse("DB_TIMEOUT", "30").toInt
    new DatabaseConfig(url, timeout)
  }
}

I personally find this much cleaner than overloading constructors. It gives the creation methods descriptive names (like fromEnv), which makes the call site much more readable for anyone else diving into your codebase.




📋 Practical Task

Implementing a Secure Token Parser

You are building a security module for an API. You need to create a SessionToken class that holds a tokenString and an expiryDate. However, creating a session token shouldn't be as simple as calling a constructor; it requires validation to ensure the token follows a specific format (e.g., it must start with "SEC-").

Your task is to:

  • Create a case class SessionToken with the required fields.
  • Create a companion object for SessionToken.
  • Inside the companion object, implement an apply method that takes a String. If the string starts with "SEC-", it should return a SessionToken instance. If it doesn't, it should throw an IllegalArgumentException.
  • Add a secondary factory method in the companion object called createGuestToken that returns a SessionToken with a hardcoded guest string and a default expiry date.

Test your implementation by attempting to create a valid token, an invalid token (which should crash), and a guest token.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.