Bird
0
0

Given a list of Any objects, write a Kotlin function using when with smart casts to return a list of strings describing each element's type and value. What is the correct implementation?

hard📝 Application Q15 of 15
Kotlin - Control Flow as Expressions
Given a list of Any objects, write a Kotlin function using when with smart casts to return a list of strings describing each element's type and value. What is the correct implementation?
fun describeList(items: List): List {
    return items.map { item ->
        when (item) {
            is String -> "String of length ${'$'}{item.length}"
            is Int -> "Int with value ${'$'}item"
            else -> "Unknown type"
        }
    }
}
ACorrect as is, smart casts allow using item.length and item directly
BNeeds explicit casts like (item as String).length and (item as Int)
CCannot use smart casts inside lambda expressions
DMust use if-else instead of when for smart casts
Step-by-Step Solution
Solution:
  1. Step 1: Check smart cast usage in when

    The when expression smart casts item to String or Int automatically after type check.
  2. Step 2: Confirm lambda and map usage

    Inside the lambda, smart casts work normally, so accessing item.length and item is valid without explicit casts.
  3. Final Answer:

    Correct as is, smart casts allow using item.length and item directly -> Option A
  4. Quick Check:

    Smart casts work inside lambdas and when [OK]
Quick Trick: Smart casts work inside lambdas and when blocks [OK]
Common Mistakes:
MISTAKES
  • Adding unnecessary explicit casts
  • Thinking smart casts don't work in lambdas
  • Replacing when with if-else unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes