Bird
0
0

Which of the following is the correct way to declare a Kotlin function with a default parameter value?

easy📝 Syntax Q12 of 15
Kotlin - Functions
Which of the following is the correct way to declare a Kotlin function with a default parameter value?
Afun add(a: Int, b: Int default 5) { return a + b }
Bfun add(a: Int = 5, b: Int) { return a + b }
Cfun add(a: Int, b: Int) = a + b = 5
Dfun add(a: Int, b: Int = 5) { return a + b }
Step-by-Step Solution
Solution:
  1. Step 1: Check Kotlin syntax for default parameters

    In Kotlin, default values are assigned using = after the parameter type, like b: Int = 5.
  2. Step 2: Validate each option

    fun add(a: Int, b: Int = 5) { return a + b } correctly uses b: Int = 5. fun add(a: Int = 5, b: Int) { return a + b } places default before non-default parameter, which is allowed but can cause ambiguity if called without named arguments. Options A and C have invalid syntax.
  3. Final Answer:

    fun add(a: Int, b: Int = 5) { return a + b } -> Option D
  4. Quick Check:

    Default value syntax = parameter: Type = value [OK]
Quick Trick: Use '=' after type to set default value [OK]
Common Mistakes:
MISTAKES
  • Placing default value before type
  • Using 'default' keyword instead of '='
  • Assigning default outside parameter list

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes