Challenge - 5 Problems
Companion vs Top-level Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of companion object function call
What is the output of this Kotlin code when calling
MyClass.greet()?Kotlin
class MyClass { companion object { fun greet() = "Hello from companion" } } fun main() { println(MyClass.greet()) }
Attempts:
2 left
💡 Hint
Companion object functions can be called using the class name.
✗ Incorrect
The function greet() is inside the companion object of MyClass, so it can be called as MyClass.greet(). This prints the string returned by greet().
🧠 Conceptual
intermediate2:00remaining
Choosing between companion and top-level functions
Which situation is best suited for using a companion object function instead of a top-level function in Kotlin?
Attempts:
2 left
💡 Hint
Think about encapsulation and access to class internals.
✗ Incorrect
Companion object functions can access private members of their class, so they are suitable when the function logically belongs to the class and needs such access. Top-level functions are better for unrelated utilities.
❓ Predict Output
advanced2:00remaining
Output of top-level vs companion function with same name
What is the output of this Kotlin code?
Kotlin
fun greet() = "Hello from top-level" class MyClass { companion object { fun greet() = "Hello from companion" } } fun main() { println(greet()) println(MyClass.greet()) }
Attempts:
2 left
💡 Hint
Top-level and companion functions with the same name are called differently.
✗ Incorrect
The top-level greet() is called directly, printing "Hello from top-level". The companion greet() is called with MyClass.greet(), printing "Hello from companion".
🔧 Debug
advanced2:00remaining
Why does this companion object function cause a compilation error?
Consider this Kotlin code snippet:
class MyClass {
companion object {
fun printMessage() {
println(message)
}
}
private val message = "Hello"
}
Why does this code cause a compilation error?
Attempts:
2 left
💡 Hint
Think about what companion objects can access inside a class.
✗ Incorrect
Companion objects are like static members and cannot access instance properties directly. 'message' is an instance property, so the companion object function cannot access it.
🧠 Conceptual
expert2:00remaining
Best practice for organizing utility functions in Kotlin
You have several utility functions that do not require access to any class members. What is the best practice for organizing these functions in Kotlin?
Attempts:
2 left
💡 Hint
Consider simplicity and idiomatic Kotlin style.
✗ Incorrect
Top-level functions are the idiomatic way in Kotlin to define utility functions that do not need class context. Companion objects or object declarations are used when grouping related functions or needing static-like behavior.