companion object
- Kotlin course
- Intermediate
- Lesson 31/116
- 5 min
Learn class-level members with companion object.
companion object
A companion object is a single object nested inside a class. Its members are called through the class name; no class instance is needed. This is convenient for factory methods and constants.
Example: class User(val name: String) { companion object { val default = "guest" } }. Here User.default is accessed directly. A companion object is a singleton tied to a class; there is one per class. It is similar to static members in Java but is still a real object.
Factory method
A common use of a companion object is factory methods. It hides how the class is instantiated and creates instances from a single point.
Example: class User(val name: String) { companion object { fun default() = User("guest") } }. This enables User.default(); it always returns a User named "guest". Instead of writing User("guest") outside, you call the factory method. This keeps construction logic in one place.
Practice Define the User factory method
Define a class User(val name: String). Add a companion object block with a fun default(): User method that returns User("guest"). In main print User.default().name with println.
Starter code
// Define the User class
// a class-level singleton block with a default factory method
// call default in main and print nameSample solution
class User(val name: String) {
companion object {
fun default(): User = User("guest")
}
}
fun main() {
println(User.default().name)
}Expected output
guest
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the companion object parts
| Term | Meaning |
|---|---|
companion object |
Class-level singleton |
val default |
Class-level constant |
User.default |
Access via class name |
one per class |
Instance count |
2 How are members of a <strong>companion object</strong> accessed?
- Through a class instance
- With the new keyword
- Only from a subclass
- Directly via the class name Correct answer
Explanation: Members of a companion object are called directly via the class name.
3 Complete the companion object definition
class User(val name: String) {
____ object {
fun default() = User("guest")
}
}
class User(val name: String) {
companion object {
fun default() = User("guest")
}
}
Explanation: companion object declares a class-level singleton.