Challenge - 5 Problems
Kotlin Type Checking Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code using 'is' operator?
Consider the following Kotlin code snippet. What will it print?
Kotlin
fun main() { val obj: Any = "Hello" if (obj is String) { println(obj.length) } else { println("Not a string") } }
Attempts:
2 left
💡 Hint
Remember that 'is' checks if the object is of a certain type and smart casts it.
✗ Incorrect
The variable 'obj' is of type Any but holds a String. The 'is String' check succeeds, so inside the if block, 'obj' is smart cast to String and 'obj.length' prints 5.
❓ Predict Output
intermediate2:00remaining
What does this Kotlin code print when using 'is' with nullable type?
Analyze the output of this Kotlin code snippet:
Kotlin
fun main() { val obj: Any? = null if (obj is String) { println("String with length ${obj.length}") } else { println("Not a string or null") } }
Attempts:
2 left
💡 Hint
Check how 'is' operator behaves with null values.
✗ Incorrect
The variable 'obj' is null. The 'is String' check returns false for null, so the else block runs printing 'Not a string or null'.
🔧 Debug
advanced2:00remaining
Why does this Kotlin code cause a compilation error?
Examine the code below and identify why it does not compile:
Kotlin
fun main() { val obj: Any = 123 if (obj is String) { println(obj.length) } else { println(obj.length) } }
Attempts:
2 left
💡 Hint
Consider what type 'obj' has in the else block and if 'length' is accessible.
✗ Incorrect
In the else block, 'obj' is still of type 'Any' which does not have a 'length' property, causing a compilation error.
🧠 Conceptual
advanced2:00remaining
What is the behavior of 'is' operator with inheritance in Kotlin?
Given the classes below, what will the output be?
Kotlin
open class Animal class Dog : Animal() fun main() { val pet: Animal = Dog() if (pet is Dog) { println("It's a dog") } else { println("It's not a dog") } }
Attempts:
2 left
💡 Hint
The 'is' operator checks the actual object type, not the declared type.
✗ Incorrect
The variable 'pet' is declared as Animal but holds a Dog instance. The 'is Dog' check returns true, so it prints 'It's a dog'.
📝 Syntax
expert2:00remaining
Which option causes a syntax error in Kotlin when using 'is' operator?
Identify which code snippet below will cause a syntax error:
Attempts:
2 left
💡 Hint
Check the syntax of the if statement in Kotlin.
✗ Incorrect
Option B misses parentheses around the condition, which is required in Kotlin if statements, causing a syntax error.