Bird
0
0

Identify the error in this Kotlin function declaration:

medium📝 Debug Q14 of 15
Kotlin - Functions
Identify the error in this Kotlin function declaration:
fun greet(name: String = "User", age: Int) {
    println("Hello, $name! You are $age years old.")
}
ACannot use default values with String parameters.
BDefault parameter must be last or followed by named arguments.
CFunction must return a value if default parameters are used.
DNo error, function is correct.
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter order rules

    In Kotlin, parameters with default values should be placed after parameters without default values, or you must use named arguments when calling.
  2. Step 2: Analyze given function

    Here, name has a default but comes before age which has no default. This causes a problem when calling without named arguments.
  3. Final Answer:

    Default parameter must be last or followed by named arguments. -> Option B
  4. Quick Check:

    Default parameters after non-default or use named args [OK]
Quick Trick: Place default parameters after non-default ones [OK]
Common Mistakes:
MISTAKES
  • Putting default parameters before required ones
  • Assuming all parameters can have defaults anywhere
  • Ignoring named argument calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes