Companion object in Kotlin
Level 4160 keystrokes
Members of a companion object belong to the class, not to an instance, so they are called with the class name, like static members in Java. count is shared, and each increment() adds 1 to it.
Kotlin code
// A class whose only members are in its companion object1class Counter { // A single object tied to the class; its members are used via Counter.2 companion object { // One counter shared by the whole class, starting at 03 var count = 0 // Pre-increment: adds 1 first, then returns the new value4 fun increment() = ++count5 }6}7 // Called on the class name without an instance: prints 18println(Counter.increment())// The shared counter keeps its value: prints 29println(Counter.increment())// Read the property directly: prints 210println(Counter.count)Output
1 2 2
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
(× 6)× 6.× 3{× 2}× 2+× 2=× 2