0
0
Kotlinprogramming~20 mins

Companion objects as static alternatives in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Companion Object Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
Anull
BCompilation error: Cannot access companion object property directly
CHello, Kotlin!
DRuntime exception
Attempts:
2 left
💡 Hint
Companion object properties can be accessed using the class name.
Predict Output
intermediate
2: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))
}
A12
BCompilation error: Cannot call companion object function like this
C0
DRuntime exception
Attempts:
2 left
💡 Hint
Companion object functions behave like static methods.
🔧 Debug
advanced
2: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)
}
ACannot access companion object property from init block
BThe init block cannot assign values to companion object properties
CCompanion object cannot have properties
DProperty 'name' in companion object must be initialized or declared abstract
Attempts:
2 left
💡 Hint
Companion object properties need initialization at declaration or in an init block inside the companion object.
🧠 Conceptual
advanced
2:30remaining
Companion object vs static in Kotlin
Which statement correctly describes the difference between Kotlin companion objects and Java static members?
ACompanion objects are compiled as static members in Java bytecode with no object instance.
BCompanion objects are real objects and can implement interfaces, unlike Java static members.
CCompanion objects cannot have functions, only properties.
DCompanion objects are only accessible through instances of the class.
Attempts:
2 left
💡 Hint
Think about how companion objects behave as objects themselves.
Predict Output
expert
3: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)
}
A42
BCompilation error: Cannot access private constructor
CRuntime exception
Dnull
Attempts:
2 left
💡 Hint
Companion objects can access private constructors of their class.