📖 Scenario: You are building a simple app that creates different types of vehicles. Each vehicle has a name and a type. You want to use the factory pattern with companion objects to create vehicles easily.
🎯 Goal: Build a Kotlin program that uses a companion object as a factory to create Vehicle objects with different types.
📋 What You'll Learn
Create a Vehicle class with name and type properties
Add a companion object inside Vehicle with a factory method create
The factory method should take name and type as parameters and return a Vehicle object
Use the factory method to create a vehicle
Print the vehicle's details
💡 Why This Matters
🌍 Real World
Factories help create objects in a controlled way, useful in apps that manage many similar objects like vehicles, users, or products.
💼 Career
Understanding factory patterns and companion objects is important for Kotlin developers to write clean, maintainable, and scalable code.
Progress0 / 4 steps
1
Create the Vehicle class
Create a Kotlin class called Vehicle with two properties: name of type String and type of type String. Use a primary constructor to set these properties.
Kotlin
Hint
Use class Vehicle(val name: String, val type: String) to define the class and its properties.
2
Add a companion object with a factory method
Inside the Vehicle class, add a companion object. Inside it, create a function called create that takes two parameters: name and type, both of type String. The function should return a new Vehicle object using these parameters.
Kotlin
Hint
Use companion object and define fun create(name: String, type: String): Vehicle inside it.
3
Use the factory method to create a Vehicle
Outside the Vehicle class, create a variable called car and assign it the result of calling Vehicle.create with "Car" as the name and "Sedan" as the type.
Kotlin
Hint
Call Vehicle.create("Car", "Sedan") and assign it to car.
4
Print the vehicle details
Write a println statement to print the text: "Vehicle: [name], Type: [type]" using the car object's name and type properties. Use a Kotlin string template.
Kotlin
Hint
Use println("Vehicle: ${car.name}, Type: ${car.type}") to print the details.
Practice
(1/5)
1. What is the main purpose of using a companion object in Kotlin's factory pattern?
easy
A. To provide a place for factory methods that create instances
B. To allow multiple constructors in a class
C. To make the class inherit from another class
D. To store instance variables for each object
Solution
Step 1: Understand companion objects
Companion objects in Kotlin are used to hold methods and properties related to the class but not tied to an instance.
Step 2: Role in factory pattern
In the factory pattern, companion objects provide factory methods to create instances, especially when constructors are private.
Final Answer:
To provide a place for factory methods that create instances -> Option A
Quick Check:
Companion object = factory methods [OK]
Hint: Companion objects hold factory methods for instance creation [OK]
Common Mistakes:
Thinking companion objects store instance variables
Expecting compilation error due to private constructor
Thinking create() returns null
Confusing runtime exception with private constructor
4. Identify the error in this Kotlin factory pattern code:
class User private constructor(val id: Int) {
companion object {
fun create(id: Int): User {
User(id)
}
}
}
medium
A. Companion object cannot access private constructor
B. Constructor should not be private
C. Function create() should be outside companion object
D. Missing return statement in create() method
Solution
Step 1: Check create() method body
The create() method calls User(id) but does not return the created object.
Step 2: Understand Kotlin function return rules
Functions must explicitly return a value unless they are Unit (void). Here, create() should return the new User instance.
Final Answer:
Missing return statement in create() method -> Option D
Quick Check:
Factory method must return created object [OK]
Hint: Always return the new instance in factory methods [OK]
Common Mistakes:
Assuming constructor can't be private for companion access
Placing factory method outside companion object
Forgetting return keyword in factory method
5. Given a Kotlin class with a private constructor and a companion object factory, how can you modify the factory method to return a default instance when input is invalid (e.g., empty string)?
class Device private constructor(val model: String) {
companion object {
fun create(model: String): Device {
return Device(model)
}
}
}
hard
A. Throw an exception inside create() if model is empty
B. Make constructor public and handle validation outside
C. Add a condition in create() to return Device("Unknown") if model is empty
D. Remove companion object and use secondary constructor
Solution
Step 1: Understand the problem
The factory method should handle invalid input by returning a default instance instead of failing.
Step 2: Modify create() method
Add a check: if model is empty, return Device("Unknown"), else return Device(model).
Step 3: Why this works
This approach keeps constructor private, centralizes instance creation, and handles invalid input gracefully.
Final Answer:
Add a condition in create() to return Device("Unknown") if model is empty -> Option C
Quick Check:
Factory method handles invalid input with default instance [OK]
Hint: Use if-check in factory to return default instance on invalid input [OK]
Common Mistakes:
Making constructor public defeats factory pattern
Throwing exception instead of default instance
Removing companion object loses factory benefits
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.