Challenge - 5 Problems
Named Companion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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) }
Attempts:
2 left
💡 Hint
Access the property using the named companion object.
✗ Incorrect
The companion object named Factory holds the property 'value'. Accessing it via Example.Factory.value prints 42.
🧠 Conceptual
intermediate1:30remaining
Purpose of naming a companion object
Why would you name a companion object in Kotlin instead of leaving it unnamed?
Attempts:
2 left
💡 Hint
Think about how naming affects code readability and access.
✗ Incorrect
Naming a companion object gives it a clear identifier, improving readability and allowing explicit access like ClassName.CompanionName.
🔧 Debug
advanced2: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) }
Attempts:
2 left
💡 Hint
Check if the companion object has the name you are using.
✗ Incorrect
The companion object is unnamed, so accessing it as Sample.Factory causes a compilation error: Unresolved reference.
📝 Syntax
advanced1: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?
Attempts:
2 left
💡 Hint
Remember the keyword order for companion object naming.
✗ Incorrect
The correct syntax is 'companion object Factory' inside the class to name the companion object Factory.
🚀 Application
expert2: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) }
Attempts:
2 left
💡 Hint
Use the named companion object to call the factory method.
✗ Incorrect
Since the companion object is named Creator, you must call the factory method as User.Creator.create("Alice").