Bird
0
0

Which of the following is the correct declaration and implementation?

hard📝 Application Q8 of 15
Kotlin - Functions
You want to declare a Kotlin function combineNames that takes two String parameters: first and last, and returns a single String formatted as "First Last". Which of the following is the correct declaration and implementation?
Afun combineNames(first: String, last: String) { println("$first $last") }
Bfun combineNames(first: String, last: String): String { return last + ", " + first }
Cfun combineNames(first: String, last: String): String = "$first $last"
Dfun combineNames(first: String, last: String): Unit = "$first $last"
Step-by-Step Solution
Solution:
  1. Step 1: Check function signature

    The function must take two String parameters and return a String.
  2. Step 2: Verify return format

    fun combineNames(first: String, last: String): String = "$first $last" returns the concatenated string with a space between first and last names, matching the required format "First Last".
  3. Step 3: Eliminate incorrect options

    fun combineNames(first: String, last: String): String { return last + ", " + first } returns "Last, First" which is incorrect format.
    fun combineNames(first: String, last: String) { println("$first $last") } returns Unit and prints instead of returning.
    fun combineNames(first: String, last: String): Unit = "$first $last" returns Unit but tries to return a String, causing a type mismatch.
  4. Final Answer:

    fun combineNames(first: String, last: String): String = "$first $last" -> Option C
  5. Quick Check:

    Function returns correct formatted string [OK]
Quick Trick: Return concatenated strings with space for full name [OK]
Common Mistakes:
MISTAKES
  • Returning Unit instead of String
  • Incorrect string formatting
  • Using print instead of return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes