Kotlin

Companion Objects

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
A `companion object` inside a class hosts what other languages call "static" members. Methods + properties on the companion are callable as `Foo.bar()`, but unlike static, they're a real object you can extend or implement interfaces on.
Kotlin
Raw
class User private constructor(val id: Long, val name: String) {
    companion object {
        private var nextId = 0L
        fun create(name: String): User = User(++nextId, name)
        const val MAX_NAME_LENGTH = 50

        // Companion objects can implement interfaces too
    }
}

fun main() {
    val u = User.create("Alice")                     // calls companion factory
    println("${u.id} ${u.name}")
    println(User.MAX_NAME_LENGTH)                    // 50

    // Java callers see this as a static field:
    //   User.Companion.create("Alice")    — by default
    //   User.create("Alice")              — with @JvmStatic on the function
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.