Challenge - 5 Problems
Companion Object Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of companion object property access
What is the output of this Kotlin code?
Kotlin
class Example { companion object { val greeting = "Hello, Kotlin!" } } fun main() { println(Example.greeting) }
Attempts:
2 left
💡 Hint
Companion object properties can be accessed using the class name.
✗ Incorrect
In Kotlin, companion object members can be accessed directly via the class name without creating an instance.
❓ Predict Output
intermediate2:00remaining
Calling companion object function
What will this Kotlin program print?
Kotlin
class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } fun main() { println(Calculator.add(5, 7)) }
Attempts:
2 left
💡 Hint
Companion object functions behave like static methods.
✗ Incorrect
The add function inside the companion object can be called using the class name without creating an instance.
🔧 Debug
advanced2:30remaining
Why does this companion object code fail?
This Kotlin code produces a compilation error. What is the cause?
Kotlin
class Person { companion object { val name: String } init { name = "Alice" } } fun main() { println(Person.name) }
Attempts:
2 left
💡 Hint
Companion object properties need initialization at declaration or in an init block inside the companion object.
✗ Incorrect
The property 'name' in the companion object is declared but not initialized. Kotlin requires properties in companion objects to be initialized or abstract.
🧠 Conceptual
advanced2:30remaining
Companion object vs static in Kotlin
Which statement correctly describes the difference between Kotlin companion objects and Java static members?
Attempts:
2 left
💡 Hint
Think about how companion objects behave as objects themselves.
✗ Incorrect
Companion objects are singleton objects inside a class and can implement interfaces, have their own state, and be passed around as objects, unlike static members in Java.
❓ Predict Output
expert3:00remaining
Output of companion object with private constructor
What is the output of this Kotlin program?
Kotlin
class Secret private constructor(val code: Int) { companion object { fun create(code: Int): Secret = Secret(code) } } fun main() { val secret = Secret.create(42) println(secret.code) }
Attempts:
2 left
💡 Hint
Companion objects can access private constructors of their class.
✗ Incorrect
The companion object is part of the class and can call private constructors. The create function returns an instance with code 42.