SkillByAIOpen interactive version →

Lesson 14 / 25

Object Declarations and Companion Objects

Singletons, factories and anonymous objects.

Objects instead of static

An object declaration defines a class and its single instance at once: a thread-safe, lazily initialised singleton. A companion object inside a class holds members called on the class name, such as factory functions and constants; Kotlin has no static keyword. const val declares compile-time constants of primitive or String type. Object expressions (object : Listener { ... }) create anonymous objects, similar to Java anonymous classes. data object gives a singleton a readable toString and is useful in sealed hierarchies.

A factory in a companion object

Private constructor plus validation.

class Email private constructor(val value: String) {
    companion object {
        const val MAX_LENGTH = 254

        fun parse(raw: String): Email? {
            val trimmed = raw.trim().lowercase()
            return if (trimmed.length <= MAX_LENGTH && "@" in trimmed) Email(trimmed) else null
        }
    }
}

object AppConfig {
    val baseUrl: String = System.getenv("BASE_URL") ?: "http://localhost:8080"
}

fun main() {
    val email = Email.parse(" Ada@Example.com ")      // called on the class name
    val url = AppConfig.baseUrl                        // singleton access
}

The front desk of a building

A companion object is the front desk attached to a building: you go to it by the building name to get things made, without needing a specific apartment (instance) first.

Quick check: What does an `object` declaration create?

  • A new instance on every access
  • A data class
  • An abstract class
  • A singleton: a class with exactly one lazily created instance
Answer

A singleton: a class with exactly one lazily created instance — object declarations are Kotlin singletons.