Challenge - 5 Problems
Smart Casts Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of smart cast in if condition
What is the output of this Kotlin code using smart casts in an if statement?
Kotlin
fun main() { val obj: Any = "Hello" if (obj is String) { println(obj.length) } else { println("Not a string") } }
Attempts:
2 left
💡 Hint
The variable obj is checked to be a String before accessing length.
✗ Incorrect
The if condition checks if obj is a String. Inside the if block, Kotlin smart casts obj to String, so obj.length is valid and prints 5.
❓ Predict Output
intermediate2:00remaining
Smart cast behavior in when expression
What will be printed by this Kotlin code using smart casts in a when expression?
Kotlin
fun main() { val x: Any = 42 when (x) { is String -> println("String of length ${x.length}") is Int -> println("Int doubled is ${x * 2}") else -> println("Unknown type") } }
Attempts:
2 left
💡 Hint
Check the type of x and how smart casts work in when branches.
✗ Incorrect
The variable x is an Int with value 42. The when expression smart casts x to Int in the second branch, so it prints 84.
🔧 Debug
advanced2:00remaining
Why does this smart cast fail?
Consider this Kotlin code snippet. Why does it fail to compile?
Kotlin
fun main() { var obj: Any? = "Kotlin" if (obj is String && obj.length > 3) { println(obj.length) } }
Attempts:
2 left
💡 Hint
Think about nullability and smart casts combined with logical operators.
✗ Incorrect
Smart casts do not work when the variable is nullable and used with && without explicit null check. Kotlin cannot guarantee obj is not null after the check.
📝 Syntax
advanced2:00remaining
Identify the syntax error with smart casts in when
Which option contains a syntax error related to smart casts in this Kotlin when expression?
Kotlin
fun main() { val y: Any = 10 when (y) { is String -> println(y.length) is Int -> println(y + 5) else -> println("Unknown") } }
Attempts:
2 left
💡 Hint
Check the syntax of when branches and the use of arrows.
✗ Incorrect
In Kotlin, each when branch must use '->' before the expression. Omitting '->' causes a syntax error.
🚀 Application
expert3:00remaining
Determine the number of items in the resulting map
What is the number of entries in the map produced by this Kotlin code using smart casts in when?
Kotlin
fun main() { val items: List<Any> = listOf("apple", 10, "banana", 3.14) val result = items.mapNotNull { when (it) { is String -> it.uppercase() is Int -> (it * 2).toString() else -> null } }.associateWith { it.length } println(result.size) }
Attempts:
2 left
💡 Hint
Count how many items are transformed and not filtered out.
✗ Incorrect
Only Strings and Ints are transformed; the Double is filtered out by returning null. So 3 items remain in the map.