Complete the code to check if the variable is a String using is.
fun checkType(x: Any) {
if (x [1] String) {
println("It's a string of length ${x.length}")
}
}In Kotlin, is checks if a variable is of a certain type and smart casts it inside the block.
Complete the when expression to smart cast obj to Int.
fun describe(obj: Any): String = when (obj) {
is [1] -> "Integer with value $obj"
else -> "Unknown"
}is is needed for smart cast.The when expression smart casts obj to Int when using is Int.
Fix the error by completing the if condition to smart cast value to String.
fun printLength(value: Any) {
if (value [1] String) {
println(value.length)
}
}Using is smart casts value to String inside the if block, allowing access to length.
Fill both blanks to create a dictionary comprehension that includes only strings longer than 3 characters.
val words = listOf("cat", "house", "dog", "elephant") val result = words.associateWith { it.length }.filter { it.key [1] 3 && it.key [2] String } println(result)
The filter keeps entries where the key is a String and its length is greater than 3.
Fill all three blanks to create a when expression that smart casts and returns descriptions.
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"
}Using is in when smart casts input to the checked type inside each branch.