Beginner 7 min readKotlin 2.0

Kotlin Companion Object โ€” Factory Methods and Constants

A companion object is a singleton tied to a class. Access its members with ClassName.member โ€” similar to Java static members.

What You Will Learn

  • Declare companion objects
  • Store constants and factory methods
  • Implement interfaces on companions
  • Compare with Java static
  • Use @JvmStatic for Java interop

Declaring a Companion

Place companion object inside a class body. There can be only one companion per class.

Constants and Factory

kotlin
class User private constructor(val name: String) {
    companion object {
        const val MAX_NAME = 50
        fun create(name: String): User {
            require(name.length <= MAX_NAME)
            return User(name)
        }
    }
}

fun main() {
    val u = User.create("Juned")
    println("${u.name} (max ${User.MAX_NAME})")
}
Output
Juned (max 50)

Private constructor forces creation through the companion factory. const val is compile-time constant.

Best Practice: Use companion factories when construction logic is non-trivial.

Companion Implements Interface

Companions can implement interfaces โ€” useful for plugin-style APIs and testing.

Companion as Factory Interface

kotlin
interface Parser {
    fun parse(input: String): Int
}

class NumberParser private constructor() {
    companion object : Parser {
        override fun parse(input: String) = input.toInt()
    }
}

fun main() {
    println(NumberParser.parse("42"))
}
Output
42

Call parse via NumberParser.parse because the companion implements Parser.

Practice Exercise

Exercisemultiple choice

How do you access a companion object member?

Quick Quiz

Quick Quiz

How many companion objects can a class have?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-19Kotlin 2.0

Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review