Bird
0
0

What is wrong with this Kotlin function?

medium📝 Debug Q6 of 15
Kotlin - Data Types
What is wrong with this Kotlin function?
fun logMessage(): Unit {
    return 10
    println("Logging")
}
AReturning an Int value in a Unit function is invalid
BThe println statement after return is unreachable
CUnit functions cannot have a return statement
DThere is no error
Step-by-Step Solution
Solution:
  1. Step 1: Check return type compatibility

    The function declares return type Unit, so it cannot return an Int value like 10.
  2. Step 2: Analyze other issues

    While the println after return is unreachable, the main error is returning a value incompatible with Unit.
  3. Final Answer:

    Returning an Int in a Unit function is invalid -> Option A
  4. Quick Check:

    Unit functions cannot return non-Unit values [OK]
Quick Trick: Unit functions must not return values other than Unit [OK]
Common Mistakes:
MISTAKES
  • Returning values other than Unit
  • Ignoring unreachable code warnings
  • Assuming return is optional in Unit functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes