0
0
Kotlinprogramming~20 mins

Object declaration syntax in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Object Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin object declaration?
Consider the following Kotlin code. What will be printed when Main.main() is run?
Kotlin
object Counter {
    var count = 0
    fun increment() {
        count++
    }
}

fun main() {
    Counter.increment()
    Counter.increment()
    println(Counter.count)
}
A2
B0
CCompilation error
D1
Attempts:
2 left
💡 Hint
Remember that object declarations create a singleton instance.
Predict Output
intermediate
2:00remaining
What error does this Kotlin object declaration cause?
What error will this Kotlin code produce when compiled?
Kotlin
object Sample {
    val x: Int
}

fun main() {
    println(Sample.x)
}
ACompilation error: Property must be initialized or be abstract
BRuntime error: UninitializedPropertyAccessException
CPrints 0
DNo error, prints null
Attempts:
2 left
💡 Hint
Check if properties in objects need initialization.
🔧 Debug
advanced
2:00remaining
Why does this Kotlin object declaration cause a runtime error?
This Kotlin code compiles but throws an exception at runtime. What causes the error?
Kotlin
object Config {
    val data = loadData()

    fun loadData(): String {
        throw IllegalStateException("Failed to load")
    }
}

fun main() {
    println(Config.data)
}
ANull pointer exception because data is null
BException thrown during object initialization blocks main thread
CCompilation error due to missing return type
DNo error, prints "Failed to load"
Attempts:
2 left
💡 Hint
Object initialization runs when first accessed.
📝 Syntax
advanced
2:00remaining
Which Kotlin object declaration syntax is correct?
Which of the following Kotlin object declarations is syntactically correct?
A
object Logger {
    fun log(message: String)
        println(message)
}
B
object Logger {
    fun log(message: String) = {
        println(message)
    }
}
C
object Logger {
    fun log(message: String) {
        println(message)
    }
}
D
}
}    
)egassem(nltnirp        
{ )gnirtS :egassem(gol nuf    
{ reggoL tcejbo
Attempts:
2 left
💡 Hint
Check for proper function body braces and object closing brace.
🚀 Application
expert
2:00remaining
How many instances of this Kotlin object are created?
Given this Kotlin code, how many instances of Database are created during program execution?
Kotlin
object Database {
    init {
        println("Database initialized")
    }

    fun query() = "data"
}

fun main() {
    println(Database.query())
    println(Database.query())
}
AMultiple instances, one per println
BTwo instances, one per query call
CNo instances, object is static
DOne instance, initialized once
Attempts:
2 left
💡 Hint
Objects in Kotlin are singletons by design.