Skip to content
Justice Tech School

object and companion object

object makes a singleton. A companion object holds class level members.

Example
object Config { val name = "app" }
class Box private constructor(val n: Int) {
    companion object { fun of(n: Int) = Box(n) }
}
println(Config.name)
println(Box.of(3).n)

Exercise

Singleton.

 Config

Quiz Test

What does a companion object hold?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.