0
0
Kotlinprogramming~20 mins

Type checking with is operator in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Type Checking 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 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")
    }
}
A5
BNot a string
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Remember that 'is' checks if the object is of a certain type and smart casts it.
Predict Output
intermediate
2: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")
    }
}
ANullPointerException at runtime
BString with length 0
CCompilation error due to null check
DNot a string or null
Attempts:
2 left
💡 Hint
Check how 'is' operator behaves with null values.
🔧 Debug
advanced
2: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)
    }
}
AThe variable 'obj' is immutable and cannot be checked
BSmart cast does not work inside if blocks
CThe else block tries to access 'length' on 'Any' which is not guaranteed to have it
DThe 'is' operator cannot be used with 'Any' type
Attempts:
2 left
💡 Hint
Consider what type 'obj' has in the else block and if 'length' is accessible.
🧠 Conceptual
advanced
2: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")
    }
}
AIt's a dog
BIt's not a dog
CCompilation error due to inheritance
DRuntime exception
Attempts:
2 left
💡 Hint
The 'is' operator checks the actual object type, not the declared type.
📝 Syntax
expert
2:00remaining
Which option causes a syntax error in Kotlin when using 'is' operator?
Identify which code snippet below will cause a syntax error:
Aif (obj is String) println(obj.length)
Bif obj is String { println(obj.length) }
Cif (obj is String) { println(obj.length) }
Dif (obj is String) println(obj.length) else println("Not a string")
Attempts:
2 left
💡 Hint
Check the syntax of the if statement in Kotlin.