Bird
0
0

Given val doubles = listOf(2.3, 5.7, 9.1), which Kotlin code correctly creates a list of Ints by explicitly converting each Double?

hard📝 Application Q8 of 15
Kotlin - Data Types
Given val doubles = listOf(2.3, 5.7, 9.1), which Kotlin code correctly creates a list of Ints by explicitly converting each Double?
Aval ints = doubles.map { it.toInt() }
Bval ints = doubles.map { it as Int }
Cval ints = doubles.map { it.toDouble().toInt() }
Dval ints = doubles.map { it.toIntOrNull() }
Step-by-Step Solution
Solution:
  1. Step 1: Understand map transformation

    Use map to transform each element in the list.
  2. Step 2: Use explicit conversion

    toInt() converts Double to Int explicitly.
  3. Step 3: Evaluate options

    val ints = doubles.map { it.toInt() } correctly uses toInt(). val ints = doubles.map { it as Int } uses unsafe cast, causing runtime error. val ints = doubles.map { it.toDouble().toInt() } is redundant. val ints = doubles.map { it.toIntOrNull() } returns nullable Ints, which is incorrect here.
  4. Final Answer:

    val ints = doubles.map { it.toInt() } -> Option A
  5. Quick Check:

    Use map with toInt() for explicit conversion [OK]
Quick Trick: Use map { it.toInt() } for list conversion [OK]
Common Mistakes:
MISTAKES
  • Using unsafe casts instead of explicit conversion
  • Confusing nullable conversions with toIntOrNull()
  • Redundant conversions like toDouble().toInt()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes