Kotlin singletons use the object keyword—one instance per class loader. Companion objects replace Java static members on the outer class, living inside the class body.
object and companion object
object AppConfig {
const val VERSION = "1.0"
}
class Factory {
companion object {
fun create() = Factory()
}
}
From Java, companion members appear as Factory.Companion.create() unless annotated with @JvmStatic.
Compared to Java static
Java uses static on the class; Kotlin prefers companion objects and top-level functions in files for namespaced helpers.
Important interview questions and answers
- Q: object vs companion object?
A:objectis a true singleton type;companion objectis one instance tied to the outer class, often for factories and constants. - Q: How do Java callers see companion members?
A: As static-like methods on a generatedCompanionclass, or true statics with@JvmStatic.
Self-check
- What keyword declares a singleton?
- Where do factory methods often live?
Tip: Use companion object for factories; add @JvmStatic for Java Class.method() calls.
Interview prep
- object vs class?
object is a singleton instance; class needs construction.
- companion vs Java static?
Companion groups static-like members; @JvmStatic for Java.