AnyCompiler

Objects and Companion Objects

object Config { ... } declares both a class and its single instance at once — there's no separate new Config() anywhere, since only one instance can ever exist. This is Kotlin's built-in way to write a singleton, with no manual private-constructor-plus-static-getter dance.

object Config {
    val appName = "AnyCompiler"
}

fun main() {
    println(Config.appName)
}
Output
AnyCompiler

companion object

Kotlin has no static keyword at all. Instead, a class can declare a companion object — a single, special object tied to the class itself, accessed through the class name directly, the same role static plays in Java and C#.

class Counter {
    companion object {
        var count = 0
        fun increment() {
            count++
        }
    }
}

fun main() {
    Counter.increment()
    Counter.increment()
    Counter.increment()
    println(Counter.count)
}
Output
3

Next: generics — writing one class that works across many types, with the compiler still checking type safety.

Practice exercise

Define a class Counter with a companion object holding a var count starting at 0 and a fun increment(). Call increment() three times, then print Counter.count.