Challenge - 5 Problems
Any Type Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of casting Any to specific types
What is the output of this Kotlin code snippet?
Kotlin
fun main() { val value: Any = 42 when (value) { is String -> println("String: $value") is Int -> println("Int: $value") else -> println("Unknown type") } }
Attempts:
2 left
💡 Hint
Remember that 'value' is assigned an Int but typed as Any.
✗ Incorrect
The variable 'value' is of type Any but holds an Int value 42. The 'when' expression checks the actual type at runtime. Since 'value' is an Int, it matches the 'is Int' branch and prints 'Int: 42'.
🧠 Conceptual
intermediate2:00remaining
Why is Any the universal base type in Kotlin?
Which statement best explains why Kotlin uses 'Any' as the universal base type?
Attempts:
2 left
💡 Hint
Think about inheritance and type hierarchy in Kotlin.
✗ Incorrect
'Any' is the root of the Kotlin class hierarchy. All classes inherit from 'Any' implicitly, so variables of type 'Any' can hold any non-null object.
🔧 Debug
advanced2:00remaining
Identify the runtime error with Any casting
What runtime error will this Kotlin code produce?
Kotlin
fun main() { val obj: Any = "Hello" val num: Int = obj as Int println(num) }
Attempts:
2 left
💡 Hint
Casting a String to Int directly is unsafe.
✗ Incorrect
The code tries to cast a String object to Int using 'as'. This compiles but fails at runtime with ClassCastException because the actual object is not an Int.
📝 Syntax
advanced2:00remaining
Which code snippet correctly checks type of Any?
Which of the following Kotlin snippets correctly checks if a variable of type Any holds a String and prints it?
Attempts:
2 left
💡 Hint
Remember Kotlin uses 'is' for type checking.
✗ Incorrect
Kotlin uses 'is' keyword to check type at runtime. Option D uses correct syntax. Option D uses Java syntax 'instanceof' which is invalid in Kotlin. Option D and D are invalid syntax.
🚀 Application
expert2:00remaining
Result of storing different types in a List
What will be the output of this Kotlin program?
Kotlin
fun main() { val items: List<Any> = listOf(10, "Kotlin", 3.14, true) for (item in items) { when (item) { is Int -> print("I") is String -> print("S") is Double -> print("D") is Boolean -> print("B") else -> print("?") } } }
Attempts:
2 left
💡 Hint
Check the type of each element in the list and the corresponding print letter.
✗ Incorrect
The list contains Int(10), String("Kotlin"), Double(3.14), and Boolean(true). The when expression prints 'I' for Int, 'S' for String, 'D' for Double, and 'B' for Boolean. So the output is 'ISDB'.