companion and interface
- Kotlin course
- Intermediate
- Lesson 33/116
- 5 min
Learn to implement interfaces with companion object.
companion object and interface
A companion object can implement an interface. This lets the class itself act as a factory; it can be called through an interface reference.
Example: interface Factory<T> { fun create(): T }; class User(val name: String) { companion object : Factory<User> { override fun create() = User("guest") } }. Here User.create() returns a User. You can also write val f: Factory<User> = User; the companion object is itself an object. This is useful for dependency injection and testability.
The Factory<T> interface
A Factory<T> interface declares a method that produces a value of some type. A class's companion object implements this interface to take the factory role.
Example: interface Factory<T> { fun create(): T }. The User class implements it via companion object : Factory<User> { override fun create() = User("guest") }. Calling User.create().name returns guest. A generic factory interface lets different classes produce instances through a common contract. Passing a fake factory in tests becomes easy.
Practice A companion object implementing Factory<T>
Define a generic interface Factory<T> with a fun create(): T method. Define a class User(val name: String); implement via companion object : Factory<User> with override fun create() = User("guest"). In main print User.create().name with println.
Starter code
// Define the Factory<T> generic interface
// implement it for User via a class-level block
// call create in main and print nameSample solution
interface Factory<T> {
fun create(): T
}
class User(val name: String) {
companion object : Factory<User> {
override fun create() = User("guest")
}
}
fun main() {
println(User.create().name)
}Expected output
guest
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a companion object implementing an interface provide?
- The class creates multiple instances
- The class name can be assigned to an interface reference Correct answer
- Inheritance chain shortens
- Abstract methods are deleted
Explanation: When a companion object implements an interface, the class name can be assigned to an interface reference.
2 Match the companion + interface parts
| Term | Meaning |
|---|---|
interface Factory<T> |
Interface definition |
companion object : Factory<User> |
Implementation |
override fun create |
Method implementation |
User.create() |
Factory call |
3 Complete the companion + interface definition
class User(val name: String) {
companion object : ____<User> {
override fun create() = User("guest")
}
}
class User(val name: String) {
companion object : Factory<User> {
override fun create() = User("guest")
}
}
Explanation: companion object : Factory<User> implements the interface.