Static members / companion objects

Static members are shared between all instances of class.

In Kotlin static members implemented through companion object. Every class can have only one companion object. You can access to companion object members directly within the class and through operator . after the class name from outside.

By default, a new anonymous class will be created for the companion object. But you can specify the name, its parent class, or interfaces, as for ordinary object.

integrate with Java

A @JvmStatic annotation marks method of object or companion object as static method for Java.

A @JvmField annotation marks field of object or companion object as static property for Java.

A lateinit and const modifiers also mark field of object or companion object as static property for Java.

class Key(val value: Int) {
    companion object {
        @JvmField
        val COMPARATOR: Comparator<Key> = compareBy<Key> { it.value }
    }
}

object Singleton { lateinit var provider: Provider }

object Obj { const val CONST = 1 }

class C {
    companion object {
        const val VERSION = 9
    }
}

// for example declared in file example.kt
const val MAX = 239

In Java you can use them in following way:

Key.COMPARATOR.compare(key1, key2);
Singleton.provider = new Provider();
int const = Obj.CONST;
int max = ExampleKt.MAX;
int version = C.VERSION;