0
0
Kotlinprogramming~20 mins

Factory pattern with companion objects in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Factory Pattern Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of factory method with companion object
What is the output of this Kotlin code using a factory pattern with a companion object?
Kotlin
class Vehicle private constructor(val type: String) {
    companion object {
        fun create(type: String): Vehicle {
            return Vehicle(type)
        }
    }
    override fun toString() = "Vehicle type: $type"
}

fun main() {
    val car = Vehicle.create("Car")
    println(car)
}
AVehicle type: Car
BVehicle type: Vehicle
CCar
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the companion object creates an instance with the given type.
Predict Output
intermediate
2:00remaining
Output when factory method returns different subclasses
What will be printed when running this Kotlin code that uses a factory method in a companion object to return different subclasses?
Kotlin
sealed class Animal {
    abstract fun sound(): String
    companion object {
        fun create(type: String): Animal = when(type) {
            "dog" -> Dog()
            "cat" -> Cat()
            else -> throw IllegalArgumentException("Unknown animal")
        }
    }
}

class Dog : Animal() {
    override fun sound() = "Woof"
}

class Cat : Animal() {
    override fun sound() = "Meow"
}

fun main() {
    val animal = Animal.create("cat")
    println(animal.sound())
}
AMeow
BWoof
CCompilation error
DIllegalArgumentException
Attempts:
2 left
💡 Hint
Check which subclass is created by the factory method for the input "cat".
🔧 Debug
advanced
2:00remaining
Identify the error in this factory pattern with companion object
This Kotlin code tries to implement a factory pattern with a companion object but fails to compile. What is the cause of the error?
Kotlin
class Product private constructor(val name: String) {
    companion object {
        fun create(name: String): Product {
            return Product(name)
        }
    }
}

fun main() {
    val p = Product.create("Book")
    println(p.name)
}
AThe constructor cannot be private in this pattern
BThe create function does not return the created Product instance
CThe companion object cannot access private constructors
DThe println statement is invalid
Attempts:
2 left
💡 Hint
Check the return type and value of the create function.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a factory method in a companion object?
Choose the Kotlin code snippet that correctly defines a factory method named 'build' inside a companion object that returns an instance of the class 'Gadget'.
A
companion object {
    fun build(): Gadget {
        return Gadget()
    }
}
B
companion object {
    fun build() {
        return Gadget()
    }
}
C
companion object {
    fun build() = Gadget
}
D
companion object {
    fun build(): Gadget = Gadget()
}
Attempts:
2 left
💡 Hint
The factory method must return an instance of Gadget explicitly.
🚀 Application
expert
3:00remaining
How many instances are created and what is printed?
Consider this Kotlin code using a factory pattern with companion object and caching. How many instances of 'CacheItem' are created, and what is printed?
Kotlin
class CacheItem private constructor(val id: Int) {
    companion object {
        private val cache = mutableMapOf<Int, CacheItem>()
        fun get(id: Int): CacheItem {
            return cache.getOrPut(id) { CacheItem(id) }
        }
    }
    override fun toString() = "CacheItem #$id"
}

fun main() {
    val a = CacheItem.get(1)
    val b = CacheItem.get(2)
    val c = CacheItem.get(1)
    println(a === c)
    println(a === b)
    println(a)
    println(b)
}
A1 instance created; prints: true, true, CacheItem #1, CacheItem #1
B3 instances created; prints: false, false, CacheItem #1, CacheItem #2
C2 instances created; prints: true, false, CacheItem #1, CacheItem #2
D2 instances created; prints: false, true, CacheItem #1, CacheItem #2
Attempts:
2 left
💡 Hint
Check how many times the constructor is called and how getOrPut works.