0
0
Kotlinprogramming~10 mins

Factory pattern with companion objects in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Factory pattern with companion objects
Call factory method
Companion object method
Decide which class to create
Create instance
Return instance to caller
The factory method inside the companion object decides which class instance to create and returns it when called.
Execution Sample
Kotlin
class Animal private constructor(val type: String) {
    companion object {
        fun create(type: String): Animal = when(type) {
            "dog" -> Animal("dog")
            "cat" -> Animal("cat")
            else -> Animal("unknown")
        }
    }
}

val pet = Animal.create("dog")
This code uses a companion object factory method to create Animal instances based on a type string.
Execution Table
StepActionInputDecisionCreated InstanceReturned Value
1Call factory methodtype = "dog"Check type value
2Match type in when"dog"Matches "dog" caseAnimal("dog")
3Create Animal instanceAnimal(type="dog")
4Return instanceAnimal(type="dog")
5Assign to variablepet = Animal(type="dog")
6EndFactory method returns Animal instance
💡 Factory method returns the created Animal instance and execution ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
typeundefined"dog""dog""dog""dog""dog"
instancenullnullnullAnimal(type="dog")Animal(type="dog")Animal(type="dog")
petnullnullnullnullAnimal(type="dog")Animal(type="dog")
Key Moments - 3 Insights
Why do we use a companion object for the factory method?
The companion object allows calling the factory method directly on the class without creating an instance first, as shown in step 1 of the execution_table.
What happens if the input type does not match any case?
The else branch creates an Animal with type "unknown", ensuring the factory always returns an instance, as implied in the when expression in step 2.
Why is the constructor private?
Making the constructor private forces users to create instances only through the factory method, controlling object creation as seen in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what instance is created at step 3?
AAnimal(type="unknown")
BAnimal(type="cat")
CAnimal(type="dog")
DNo instance created
💡 Hint
Check the 'Created Instance' column at step 3 in the execution_table.
At which step is the factory method called?
AStep 1
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Action' column to find when the factory method is first called.
If the input type was "bird", what would be the returned instance type?
A"dog"
B"unknown"
C"cat"
DNo instance returned
💡 Hint
Refer to the else branch in the when expression in the execution_sample code.
Concept Snapshot
Factory pattern with companion objects in Kotlin:
- Use companion object to hold factory methods.
- Factory method decides which instance to create.
- Private constructor restricts direct instantiation.
- Call factory method via ClassName.method() syntax.
- Ensures controlled and flexible object creation.
Full Transcript
This example shows how Kotlin's companion object can hold a factory method to create instances of a class. The class Animal has a private constructor, so it cannot be created directly. Instead, the companion object has a create() method that takes a type string. It uses a when expression to decide which Animal to create: dog, cat, or unknown. When we call Animal.create("dog"), the factory method runs, matches the "dog" case, creates an Animal with type "dog", and returns it. The variable pet then holds this instance. This pattern helps control how objects are made and keeps creation logic in one place.