Bird
0
0

Given a map val data = mapOf("a" to 1, "b" to 2.5, "c" to 3), how do you convert all values to Double explicitly?

hard📝 Application Q9 of 15
Kotlin - Data Types
Given a map val data = mapOf("a" to 1, "b" to 2.5, "c" to 3), how do you convert all values to Double explicitly?
Aval converted = data as Map<String, Double>
Bval converted = data.mapValues { it.value as Double }
Cval converted = data.mapValues { it.value.toDouble() }
Dval converted = data.toDouble()
Step-by-Step Solution
Solution:
  1. Step 1: Understand map value conversion

    Use mapValues with explicit toDouble() to convert all values.
  2. Step 2: Check options

    val converted = data.mapValues { it.value.toDouble() } correctly converts values. val converted = data as Map tries unsafe cast. val converted = data.mapValues { it.value as Double } uses 'as' which may fail. val converted = data.toDouble() is invalid.
  3. Final Answer:

    val converted = data.mapValues { it.value.toDouble() } -> Option C
  4. Quick Check:

    Use mapValues with toDouble() for map value conversion [OK]
Quick Trick: Use mapValues { it.value.toDouble() } to convert map values [OK]
Common Mistakes:
MISTAKES
  • Trying to cast map directly
  • Using 'as' for conversion
  • Calling toDouble() on map

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes