0
0
Kotlinprogramming~10 mins

Safe casts with as? 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 safely cast 'obj' to String using 'as?'.

Kotlin
val str = obj [1] String
Drag options to blanks, or click blank then click option'
Aas
Bis
Cas?
Dto
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'as' which throws an exception if the cast fails.
Using 'is' which checks type but does not cast.
Using 'to' which is not a cast operator.
2fill in blank
medium

Complete the code to safely cast 'item' to Int and assign to 'number'.

Kotlin
val number: Int? = item [1] Int
Drag options to blanks, or click blank then click option'
Aas?
Bis
Cas
Dto
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'as' which throws an exception if cast fails.
Using 'is' which only checks type but does not cast.
Using 'to' which is not a cast operator.
3fill in blank
hard

Fix the error in the code by replacing the cast operator with a safe cast.

Kotlin
val text = data [1] String
Drag options to blanks, or click blank then click option'
Aas?
Bis
Cas
Dto
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'as' which throws exceptions on failure.
Using 'is' which does not cast but only checks type.
4fill in blank
hard

Fill both blanks to create a safe cast and check if the result is null.

Kotlin
val result = value [1] String
if (result [2] null) {
    println("Cast succeeded")
}
Drag options to blanks, or click blank then click option'
Aas?
B==
C!=
Das
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'as' instead of 'as?' causing exceptions.
Using '==' instead of '!=' to check for null.
5fill in blank
hard

Fill all three blanks to safely cast 'input' to Double, check if not null, and print the value.

Kotlin
val number = input [1] Double
if (number [2] null) {
    println("Number is: [3]")
}
Drag options to blanks, or click blank then click option'
Aas?
B!=
Cnumber
Das
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'as' instead of 'as?'.
Checking '==' null instead of '!=' null.
Printing a wrong variable name.