Start learning free

LESSON 29 OF 70 · OBJECT-ORIENTED PROGRAMMING

Static Members in Kotlin: companion object and init

Practice Read the full explanation

TL;DR:

Kotlin has no static keyword. Class-level members live in a companion object inside the class, and you reach them through the class name: Dog.count. An init block runs every time an object is created.

You start with:

class Dog(val name: String) {
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Inside Dog, add a companion object with var count = 0.
  • Add an init block that does count++, so every new Dog is counted.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.count.

class Dog(val name: String) {
    companion object {
        var count = 0
    }
    init {
        count++
    }
}

class Solution {
    fun mainFunction() {
        val rex = Dog("Rex")
        val buddy = Dog("Buddy")
        println(Dog.count)
        val third = Dog("Max")
        println(Dog.count)
        println(third.name)
        Dog("Luna")
        println(Dog.count)
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · OBJECT-ORIENTED PROGRAMMING

    Static Members in Kotlin, explained

    What static members are

    Most members of a class belong to each object. Every Dog has its own name. Sometimes you need data that belongs to the class as a whole, shared by all objects, such as a counter of how many objects exist. Many languages call this a static member.

    Kotlin has no static keyword. Instead, a class can contain one companion object, and whatever is declared inside it belongs to the class itself. You reach it through the class name: Dog.count, not through an object.

    The lesson's task

    The editor starts with a Dog class that has only a name, and a Solution class with a mainFunction that you must not change. That function creates Rex and Buddy and prints Dog.count, creates Max, prints the counter and Max's name, creates Luna and prints the counter once more. The program doesn't compile at first, because Dog.count doesn't exist yet. Your job is to create it so that the output is:

    2
    3
    Max
    4
    

    The counter starts at 0 before any dog exists and goes up by exactly 1 for every dog created, whatever its name.

    Step by step

    1. Open a companion object. Inside Dog, write companion object { }. Everything inside belongs to the class, not to a single dog.
    2. Declare the shared counter. Inside the companion object, write var count = 0. It is a var because it will change, and it is declared once, so all dogs share the same value.
    3. Open an init block. Below the companion object, write init { }. Kotlin runs the code in an init block each time an object of the class is created.
    4. Count each new dog. Inside init, write count++. One object means one run of init, which means one increment of the shared counter.

    The solution in Kotlin

    class Dog(val name: String) {
        companion object {
            var count = 0
        }
        init {
            count++
        }
    }
    
    class Solution {
        fun mainFunction() {
            val rex = Dog("Rex")
            val buddy = Dog("Buddy")
            println(Dog.count)
            val third = Dog("Max")
            println(Dog.count)
            println(third.name)
            Dog("Luna")
            println(Dog.count)
        }
    }
    

    How the output comes about

    Before mainFunction runs, count is 0. Creating Rex and Buddy runs init twice, so the first print shows 2. Creating Max makes it 3, which is the second print, and the third print shows Max's name. Dog("Luna") is a statement that creates a dog and drops it, but the object is still created and init still runs, so the last print shows 4.

    Kotlin details worth knowing

    • Reach it through the class. Dog.count works. Writing third.count doesn't compile: a companion member isn't reachable through an object, and the compiler reports an unresolved reference.
    • Inside the class, use the bare name. The init block is inside Dog, so it writes count++ without a prefix. The class's companion is in scope there.
    • An ordinary property is per object. If var count = 0 were declared directly in the class body, outside the companion, every dog would have its own counter starting at 0, and each would read 1 after its own init. Two such objects both report 1, not 1 and 2. That is the difference the companion object makes: one value for the whole class, instead of one per object.
    • A companion can hold functions too. A function declared in the companion, such as fun describe() = "dogs: $count", is called as Dog.describe(). After two dogs are created it returns dogs: 2.
    • The shared value can be changed from outside. A public var in the companion can be assigned: after Dog.count = 10, the next dog makes it 11. In a real program you would usually make the setter private, but the lesson keeps it simple.
    • There is one companion per class, and it is created when the class is first used, not once per dog. That is why the counter starts at 0 and survives from one dog to the next.
    • Order in the class body. The companion object and the init block can appear in either order inside Dog. The counter exists in either case, because the companion belongs to the class and not to a particular object.

    Try it in the editor above: add the four lines one at a time, and the program compiles and prints the expected output once the companion object and the counter both exist.

    Common mistakes

    • Putting count in the class body. This gives each dog its own counter, and Dog.count doesn't compile.
    • Forgetting init. Without it the counter stays at 0 and every print shows 0.
    • Counting by name. The counter goes up for every dog, whatever its name, so init shouldn't test name.
    • Using val for count. A val can't be incremented, so count++ would not compile.
    • Editing mainFunction. The lesson's tests expect those lines as they are. Only Dog changes.

    Key takeaways

    • Kotlin has no static; a companion object holds the members that belong to the class.
    • Access them through the class name, as in Dog.count.
    • An init block runs for every new object, which makes it a good place to update a shared counter.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free