typestar

Objects and companions in Kotlin

Singletons with object, statics with companion object.

// object declares a singleton; companion members ride on the class.
object TrailRegistry {
    private val open = mutableSetOf("Ridgeline", "Lakeshore")
    fun isOpen(name: String) = name in open
}

class Permit private constructor(val id: Int) {
    companion object {
        const val PREFIX = "KTL"
        fun issue(n: Int) = Permit(n)
    }
}

fun main() {
    println(TrailRegistry.isOpen("Lakeshore"))
    val permit = Permit.issue(207)
    println("${Permit.PREFIX}-${permit.id}")
}

How it works

  1. object TrailRegistry declares and instantiates in one breath.
  2. A companion object holds what other languages call static members.
  3. private constructor plus Permit.issue funnels creation through a factory.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
449
Tokens
109
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 101 seconds.

Type this snippet

Step 3 of 3 in Classes & objects, step 15 of 27 in Language basics.

← Previous Next →

Objects and companions in other languages