Careeroza
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 val | val | |
|---|---|---|
| When the value is known | compile time | runtime |
| Allowed types | primitives and String | any |
| Where | top level, object, companion object | anywhere |
| Example | const val TIMEOUT_MS = 5000 | val 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).