Complete the code to declare a companion object inside the class.
class Car { [1] object { fun create() = Car() } }
In Kotlin, the keyword companion is used to declare a companion object inside a class.
Complete the factory method to create a Car instance.
class Car { companion object { fun [1](): Car { return Car() } } }
The factory method is commonly named create to indicate it returns a new instance.
Fix the error in the factory method call to create a Car instance.
fun main() {
val car = Car.[1]()
println("Car created: $car")
}The correct factory method name is create as defined in the companion object.
Fill both blanks to complete the factory pattern with a companion object and a private constructor.
class Bike private constructor() { companion object { fun [1](): Bike { return Bike() } } } fun main() { val bike = Bike.[2]() println("Bike created: $bike") }
The factory method is named create and is called as Bike.create() to create a new instance.
Fill all three blanks to implement a factory pattern with companion object, private constructor, and a property.
class Truck private constructor(val model: String) { companion object { fun [1](model: String): Truck { return Truck([2]) } } } fun main() { val truck = Truck.[3]("BigTruck") println("Truck model: ${truck.model}") }
The factory method is named create. It takes a parameter model and passes it to the private constructor. The call uses Truck.create("BigTruck").