Bird
Raised Fist0
Kotlinprogramming~20 mins

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

Choose your learning style10 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.

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

  1. 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.
  2. Step 2: Role in factory pattern

    In the factory pattern, companion objects provide factory methods to create instances, especially when constructors are private.
  3. Final Answer:

    To provide a place for factory methods that create instances -> Option A
  4. 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
  • Confusing companion objects with inheritance
  • Believing companion objects allow multiple constructors
2. Which of the following is the correct syntax to declare a private constructor in a Kotlin class?
easy
A. private class MyClass constructor() {}
B. class MyClass private constructor() {}
C. class MyClass constructor private() {}
D. class MyClass constructor() private {}

Solution

  1. Step 1: Recall Kotlin constructor syntax

    In Kotlin, the constructor keyword follows the class name, and modifiers like private come before constructor.
  2. Step 2: Identify correct placement

    The correct syntax places 'private' before 'constructor()' right after the class name.
  3. Final Answer:

    class MyClass private constructor() {} -> Option B
  4. Quick Check:

    Private constructor syntax = class MyClass private constructor() {} [OK]
Hint: Put 'private' before 'constructor()' after class name [OK]
Common Mistakes:
  • Placing 'private' after constructor parentheses
  • Putting 'private' before class keyword
  • Misordering 'constructor' and 'private'
3. What will be the output of the following Kotlin code?
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)
}
medium
A. Book
B. null
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Understand private constructor usage

    The class Product has a private constructor, so instances cannot be created directly outside the class.
  2. Step 2: Use of companion object factory method

    The companion object provides a create() method that calls the private constructor and returns a Product instance.
  3. Step 3: Output of main function

    In main(), Product.create("Book") creates an instance with name "Book". Printing p.name outputs "Book".
  4. Final Answer:

    Book -> Option A
  5. Quick Check:

    Factory method returns instance with name "Book" [OK]
Hint: Factory method returns instance; print property directly [OK]
Common Mistakes:
  • 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

  1. Step 1: Check create() method body

    The create() method calls User(id) but does not return the created object.
  2. 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.
  3. Final Answer:

    Missing return statement in create() method -> Option D
  4. 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

  1. Step 1: Understand the problem

    The factory method should handle invalid input by returning a default instance instead of failing.
  2. Step 2: Modify create() method

    Add a check: if model is empty, return Device("Unknown"), else return Device(model).
  3. Step 3: Why this works

    This approach keeps constructor private, centralizes instance creation, and handles invalid input gracefully.
  4. Final Answer:

    Add a condition in create() to return Device("Unknown") if model is empty -> Option C
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard