0
0
Kotlinprogramming~30 mins

Factory pattern with companion objects in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Factory pattern with companion objects
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use println("Vehicle: ${car.name}, Type: ${car.type}") to print the details.