Bird
0
0

Which function correctly implements this and allows calling with or without the prefix?

hard📝 Application Q15 of 15
Kotlin - Functions
You want to write a Kotlin function formatMessage that takes a message and an optional prefix with default value "Info:". It should return the combined string. Which function correctly implements this and allows calling with or without the prefix?
Afun formatMessage(prefix: String = "Info:", message: String) = "$prefix $message"
Bfun formatMessage(message: String, prefix: String) = "$prefix $message"
Cfun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message"
Dfun formatMessage(message: String = "Info:", prefix: String) = "$prefix $message"
Step-by-Step Solution
Solution:
  1. Step 1: Define function with default parameter last

    The optional parameter prefix with default value should come after the required message parameter.
  2. Step 2: Check each option

    fun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message" correctly places prefix last with default. fun formatMessage(prefix: String = "Info:", message: String) = "$prefix $message" places default before required, which can cause call issues. Options C and D lack default for prefix or have wrong order.
  3. Final Answer:

    fun formatMessage(message: String, prefix: String = "Info:") = "$prefix $message" -> Option C
  4. Quick Check:

    Default last parameter enables optional argument [OK]
Quick Trick: Put default parameters after required ones for easy calls [OK]
Common Mistakes:
MISTAKES
  • Placing default parameter before required parameter
  • Not providing default value for optional parameter
  • Confusing parameter order causing call errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes