Start learning free

LESSON 401 OF 414 · OBJECT-ORIENTED PROGRAMMING

Static Members in Kotlin in Kotlin

Practice

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

    Static Members in Kotlin

    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free