0
0
Kotlinprogramming~10 mins

Smart casts in when and if in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the variable is a String using is.

Kotlin
fun checkType(x: Any) {
    if (x [1] String) {
        println("It's a string of length ${x.length}")
    }
}
Drag options to blanks, or click blank then click option'
A==
Bas
Cis
Din
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of 'is' for type checking.
Using 'as' which is for casting, not checking.
2fill in blank
medium

Complete the when expression to smart cast obj to Int.

Kotlin
fun describe(obj: Any): String = when (obj) {
    is [1] -> "Integer with value $obj"
    else -> "Unknown"
}
Drag options to blanks, or click blank then click option'
AInt
BString
CDouble
DBoolean
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing String or Double instead of Int.
Forgetting that is is needed for smart cast.
3fill in blank
hard

Fix the error by completing the if condition to smart cast value to String.

Kotlin
fun printLength(value: Any) {
    if (value [1] String) {
        println(value.length)
    }
}
Drag options to blanks, or click blank then click option'
Ais
B==
Cas
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' which compares values, not types.
Using 'as' which is unsafe casting.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that includes only strings longer than 3 characters.

Kotlin
val words = listOf("cat", "house", "dog", "elephant")
val result = words.associateWith { it.length }.filter { it.key [1] 3 && it.key [2] String }
println(result)
Drag options to blanks, or click blank then click option'
A>
Bis
C<
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' for length comparison.
Using '==' instead of 'is' for type checking.
5fill in blank
hard

Fill all three blanks to create a when expression that smart casts and returns descriptions.

Kotlin
fun describeInput(input: Any): String = when {
    input [1] String -> "String of length ${input.length}"
    input [2] Int -> "Integer value $input"
    input [3] Boolean -> "Boolean value $input"
    else -> "Unknown type"
}
Drag options to blanks, or click blank then click option'
Ais
B==
C!=
Das
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' or '!=' instead of 'is' for type checking.
Using 'as' which casts but can throw exceptions.