Companion Objects

Class-level Members

Kotlin has no static keyword. Members that belong to the class rather than an instance go in a companion object. Call them through the class name.

Example

class User(val name: String) {
    init { count++ }

    companion object {
        const val MAX_NAME_LENGTH = 20
        var count = 0
            private set

        fun isValidName(name: String) = name.isNotBlank() && name.length <= MAX_NAME_LENGTH
    }
}

fun main() {
    println(User.isValidName("Kiran"))
    println(User.isValidName(""))
    User("A"); User("B"); User("C")
    println("Users created: ${User.count}")
    println("Limit: ${User.MAX_NAME_LENGTH}")
}

Output

true
false
Users created: 3
Limit: 20

const val

const valval
When the value is knowncompile timeruntime
Allowed typesprimitives and Stringany
Wheretop level, object, companion objectanywhere
Exampleconst val TIMEOUT_MS = 5000val startedAt = System.currentTimeMillis()

Tip: From Java code, companion functions are called as User.Companion.isValidName() unless annotated with @JvmStatic (covered under Java interoperability in the advanced level).