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
object TrailRegistrydeclares and instantiates in one breath.- A
companion objectholds what other languages call static members. private constructorplusPermit.issuefunnels creation through a factory.
Keywords and builtins used here
IntPermitStringTrailRegistryclasscompanionconstconstructorfuninisOpenissuemainobjectprivateval
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.
Step 3 of 3 in Classes & objects, step 15 of 27 in Language basics.