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 object
1class 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 0
3 var count = 0
// Pre-increment: adds 1 first, then returns the new value
4 fun increment() = ++count
5 }
6}
7
// Called on the class name without an instance: prints 1
8println(Counter.increment())
// The shared counter keeps its value: prints 2
9println(Counter.increment())
// Read the property directly: prints 2
10println(Counter.count)

Output

1
2
2
Practice typing this code

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

More Kotlin examples at level 4

← Kotlin typing practice