0
0
Kotlinprogramming~10 mins

Factory pattern with companion objects in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a companion object inside the class.

Kotlin
class Car {
    [1] object {
        fun create() = Car()
    }
}
Drag options to blanks, or click blank then click option'
Acompanion
BFactory
Cobject
DCompanion
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase 'Companion' instead of lowercase 'companion'.
Forgetting the keyword 'companion' before 'object'.
2fill in blank
medium

Complete the factory method to create a Car instance.

Kotlin
class Car {
    companion object {
        fun [1](): Car {
            return Car()
        }
    }
}
Drag options to blanks, or click blank then click option'
Acreate
Bnew
Cbuild
Dmake
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'new' which is not a function name in Kotlin.
Using unrelated method names like 'build' or 'make' without context.
3fill in blank
hard

Fix the error in the factory method call to create a Car instance.

Kotlin
fun main() {
    val car = Car.[1]()
    println("Car created: $car")
}
Drag options to blanks, or click blank then click option'
AnewCar
Bcreate
Cbuild
Dmake
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names that do not exist in the companion object.
Trying to call a constructor directly instead of using the factory method.
4fill in blank
hard

Fill both blanks to complete the factory pattern with a companion object and a private constructor.

Kotlin
class Bike private constructor() {
    companion object {
        fun [1](): Bike {
            return Bike()
        }
    }
}

fun main() {
    val bike = Bike.[2]()
    println("Bike created: $bike")
}
Drag options to blanks, or click blank then click option'
Acreate
Bbuild
Cmake
Dnew
Attempts:
3 left
💡 Hint
Common Mistakes
Using different method names for declaration and call.
Trying to call the constructor directly which is private.
5fill in blank
hard

Fill all three blanks to implement a factory pattern with companion object, private constructor, and a property.

Kotlin
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}")
}
Drag options to blanks, or click blank then click option'
Acreate
Bmodel
C"model"
DmodelName
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the parameter as a string literal instead of the variable.
Using inconsistent method names for factory method declaration and call.