CodeBlanks Logo Icon CodeBlanks

companion object

Learn class-level members with companion object.

Companion object

The companion object defines class-level members. Kotlin has no static keyword; instead, members inside a companion object are accessed through the class name.

Example: class Counter { companion object { var total = 0; fun create() = Counter() } }. You call Counter.total and Counter.create(). Each class can have only one companion object. Members are accessed through the class name, so they are usable without an instance.

Factory method

A method inside a companion object can act as a factory: it centralizes instance creation. It is useful to enforce constraints, keep counters or return different subtypes.

Example: companion object { var total = 0; fun create(): Counter { total += 1; return Counter() } }. Each call to create increments total. The companion object tracks how many instances have been produced. This is a clean way to manage setup logic without leaking it outside the class.

Practice Add a companion object to the Counter class

Define a class named Counter with a primary constructor taking val id: Int. Add a companion object containing var total: Int = 0 and a fun create(): Counter method. The create method increments total by 1 and returns Counter(total). In main call Counter.create() twice, then print Counter.total and the second instance's id.

Starter code

Main.kt
// Define the Counter class
// primary: val id: Int
// companion object: var total and fun create()
// create increments total and returns Counter(total)
// call create twice in main, print total and id

Sample solution

Main.kt
class Counter(val id: Int) {
    companion object {
        var total: Int = 0
        fun create(): Counter {
            total += 1
            return Counter(total)
        }
    }
}

fun main() {
    val a = Counter.create()
    val b = Counter.create()
    println(Counter.total)
    println(b.id)
}

Expected output

2
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which statement about companion object is correct?

  • A class can have multiple companion objects
  • Companion object members are called through the class name Correct answer
  • Companion object members are called on an instance
  • A companion object can contain only val

Explanation: Companion object members are accessed through the class name.

2 Match the companion object parts

Term Meaning
companion object Block keyword
var total = 0 Class-level state
fun create() Factory method
Counter.total Class-name access

3 Complete the companion object block

Question
class Counter {
    ____ object {
        var total = 0
    }
}
Answer
class Counter {
    companion object {
        var total = 0
    }
}

Explanation: The companion object block defines class-level members.

All lessons in Intermediate