Kotlin Tutorial · Object-Oriented Kotlin · Lesson 15 of 31

Kotlin Objects and Companion Objects

Singletons with object declarations, companion objects for factory functions, and object expressions.

Create a free account to save this page, take notes and track your progress. Sign in

object declarations

object Name { } declares a singleton: one instance, created lazily on first use and thread-safe.

A singleton object
object AppConfig {
    val version = "2.4"
    private val flags = mutableSetOf("dark-mode")
    fun isEnabled(flag: String) = flag in flags
}

fun main() {
    println(AppConfig.version)
    println(AppConfig.isEnabled("dark-mode"))
    println(AppConfig.isEnabled("beta"))
}

Output

2.4
true
false

Run this on your computer — see “Get Started” for setup.

companion objects

Kotlin has no static. Members that belong to the class rather than an instance go in a companion object, often as factory functions next to a private constructor. An object expression (object : Interface { }) creates a one-off anonymous implementation.

Companion factories and object expressions
class Temperature private constructor(val celsius: Double) {
    companion object {
        fun fromCelsius(c: Double) = Temperature(c)
        fun fromFahrenheit(f: Double) = Temperature((f - 32) * 5 / 9)
    }
    override fun toString() = "%.1f C".format(celsius)
}

interface Clickable { fun click(): String }

fun main() {
    println(Temperature.fromCelsius(21.0))
    println(Temperature.fromFahrenheit(98.6))
    val button = object : Clickable {
        override fun click() = "clicked once"
    }
    println(button.click())
}

Output

21.0 C
37.0 C
clicked once

Run this on your computer — see “Get Started” for setup.

Test yourself

Where do you put factory functions that would be static in Java?

  1. In a static block
  2. In a companion object
  3. In an init block
  4. In a data class
Show answer

Answer: In a companion object

Was this page helpful?