0
0
Kotlinprogramming~20 mins

Named companion objects in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Named Companion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing a named companion object property
What is the output of this Kotlin code?
Kotlin
class Example {
    companion object Factory {
        val value = 42
    }
}

fun main() {
    println(Example.Factory.value)
}
A42
BFactory
Cnull
DCompilation error
Attempts:
2 left
💡 Hint
Access the property using the named companion object.
🧠 Conceptual
intermediate
1:30remaining
Purpose of naming a companion object
Why would you name a companion object in Kotlin instead of leaving it unnamed?
ATo provide a specific name for better code clarity and explicit access
BTo allow multiple companion objects in the same class
CTo make the companion object private
DTo enable inheritance from the companion object
Attempts:
2 left
💡 Hint
Think about how naming affects code readability and access.
🔧 Debug
advanced
2:00remaining
Identify the error when accessing an unnamed companion object with a name
What error occurs when you try to access an unnamed companion object using a name?
Kotlin
class Sample {
    companion object {
        val data = "Hello"
    }
}

fun main() {
    println(Sample.Factory.data)
}
ACompilation succeeds and prints 'Hello'
BUnresolved reference: Factory
CNullPointerException at runtime
DType mismatch error
Attempts:
2 left
💡 Hint
Check if the companion object has the name you are using.
📝 Syntax
advanced
1:30remaining
Correct syntax to declare a named companion object
Which of the following is the correct syntax to declare a named companion object in Kotlin?
A
class MyClass {
    object companion Factory {
        val x = 10
    }
}
B
class MyClass {
    companion Factory {
        val x = 10
    }
}
C
class MyClass {
    companion object Factory {
        val x = 10
    }
}
D
class MyClass {
    companion object {
        val x = 10
    } Factory
}
Attempts:
2 left
💡 Hint
Remember the keyword order for companion object naming.
🚀 Application
expert
2:30remaining
Using named companion object to implement a factory method
Given the class below, which option correctly uses the named companion object to create an instance with a factory method?
Kotlin
class User private constructor(val name: String) {
    companion object Creator {
        fun create(name: String): User {
            return User(name)
        }
    }
}

fun main() {
    val user = ???
    println(user.name)
}
AUser.create("Alice")
BUser.Creator("Alice")
CUser.Companion.create("Alice")
DUser.Creator.create("Alice")
Attempts:
2 left
💡 Hint
Use the named companion object to call the factory method.