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.
object declarations
object Name { } declares a singleton: one instance, created lazily on first use and thread-safe.
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.
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?
In a static blockIn a companion objectIn an init blockIn a data class
Show answer
Answer: In a companion object