The factory pattern helps create objects without exposing the creation logic. Companion objects in Kotlin let us put this logic inside the class itself.
0
0
Factory pattern with companion objects in Kotlin
Introduction
When you want to control how objects of a class are created.
When you want to return different types of objects from the same method.
When you want to hide complex creation steps from the user.
When you want to create objects with some default or custom settings.
When you want to avoid calling constructors directly.
Syntax
Kotlin
class ClassName private constructor(val property: Type) { companion object { fun create(param: Type): ClassName { // creation logic return ClassName(param) } } }
The constructor is private to prevent direct creation from outside.
The companion object acts like a static factory inside the class.
Examples
Simple factory method inside companion object to create a User.
Kotlin
class User private constructor(val name: String) { companion object { fun create(name: String): User { return User(name) } } }
Factory methods to create different shapes without exposing constructor details.
Kotlin
class Shape private constructor(val type: String) { companion object { fun createCircle(): Shape = Shape("Circle") fun createSquare(): Shape = Shape("Square") } }
Sample Program
This program uses the factory pattern with companion objects to create Vehicle objects. The constructor is private, so you must use the factory methods to create vehicles.
Kotlin
class Vehicle private constructor(val type: String) { companion object { fun createCar(): Vehicle = Vehicle("Car") fun createBike(): Vehicle = Vehicle("Bike") } } fun main() { val car = Vehicle.createCar() val bike = Vehicle.createBike() println("Vehicle 1 is a ${car.type}") println("Vehicle 2 is a ${bike.type}") }
OutputSuccess
Important Notes
Using private constructors ensures objects are only created through factory methods.
Companion objects let you group factory methods inside the class for better organization.
This pattern helps keep object creation flexible and easy to change later.
Summary
The factory pattern controls object creation.
Companion objects in Kotlin provide a neat place for factory methods.
Private constructors prevent direct object creation, enforcing use of factories.