Bird
0
0

Identify the error in this Kotlin code snippet and choose the correct fix:

medium📝 Debug Q14 of 15
Kotlin - Data Types
Identify the error in this Kotlin code snippet and choose the correct fix:
val a: Int = 5
val b: Double = a
println(b)
AChange <code>val b: Double = a</code> to <code>val b: Double = a.toDouble()</code>
BChange <code>val a: Int = 5</code> to <code>val a: Double = 5</code>
CAdd explicit cast: <code>val b: Double = a as Double</code>
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Understand Kotlin's type conversion rules

    Kotlin does not allow implicit conversion from Int to Double, so val b: Double = a causes a compilation error.
  2. Step 2: Apply explicit conversion to fix the error

    Using a.toDouble() explicitly converts Int to Double, fixing the error.
  3. Final Answer:

    Change val b: Double = a to val b: Double = a.toDouble() -> Option A
  4. Quick Check:

    Explicit conversion needed for Int to Double [OK]
Quick Trick: Use toDouble() to convert Int to Double explicitly [OK]
Common Mistakes:
MISTAKES
  • Assuming implicit conversion works
  • Using 'as' cast for primitive types
  • Ignoring compilation errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes