0
0
Kotlinprogramming~20 mins

When with ranges and types in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
When Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of when with Int range check
What is the output of this Kotlin code snippet?
Kotlin
fun main() {
    val x = 15
    val result = when (x) {
        in 1..10 -> "Low"
        in 11..20 -> "Medium"
        else -> "High"
    }
    println(result)
}
ALow
BMedium
CHigh
DCompilation error
Attempts:
2 left
💡 Hint
Check which range the value 15 belongs to.
Predict Output
intermediate
2:00remaining
When with type checking
What will be printed by this Kotlin code?
Kotlin
fun main() {
    val obj: Any = "Hello"
    val output = when (obj) {
        is Int -> "Integer"
        is String -> "String"
        else -> "Unknown"
    }
    println(output)
}
AString
BInteger
CUnknown
DRuntime exception
Attempts:
2 left
💡 Hint
Check the type of obj at runtime.
Predict Output
advanced
2:00remaining
When with mixed ranges and types
What is the output of this Kotlin program?
Kotlin
fun main() {
    val input: Any = 25
    val result = when (input) {
        in 1..10 -> "Small number"
        is Int -> "Integer number"
        in 20..30 -> "Medium number"
        else -> "Other"
    }
    println(result)
}
AInteger number
BMedium number
CSmall number
DOther
Attempts:
2 left
💡 Hint
Remember that when checks branches in order and stops at the first match.
Predict Output
advanced
2:00remaining
When with smart casting and type mismatch
What will this Kotlin code print?
Kotlin
fun main() {
    val data: Any = 5.5
    val output = when (data) {
        is Int -> "Int: ${data + 1}"
        is Double -> "Double: ${data + 1}"
        else -> "Unknown type"
    }
    println(output)
}
AInt: 6
BCompilation error
CDouble: 6.5
DUnknown type
Attempts:
2 left
💡 Hint
Check the actual type of data and how smart casting works.
Predict Output
expert
3:00remaining
When with complex type and range conditions
What is the output of this Kotlin code?
Kotlin
fun main() {
    val value: Any = 42
    val result = when (value) {
        is Int -> when (value) {
            in 1..10 -> "Small Int"
            in 11..50 -> "Medium Int"
            else -> "Large Int"
        }
        is String -> "String value"
        else -> "Unknown"
    }
    println(result)
}
ALarge Int
BSmall Int
CUnknown
DMedium Int
Attempts:
2 left
💡 Hint
Look carefully at the nested when and the ranges for the Int value.