Bird
0
0

You want to write a single-expression function in Kotlin that returns the maximum of two integers. Which of the following is correct?

hard📝 Application Q8 of 15
Kotlin - Functions
You want to write a single-expression function in Kotlin that returns the maximum of two integers. Which of the following is correct?
Afun max(a: Int, b: Int) = { if (a > b) a else b }
Bfun max(a: Int, b: Int) { if (a > b) return a else return b }
Cfun max(a: Int, b: Int): Int { return if (a > b) a else b }
Dfun max(a: Int, b: Int) = if (a > b) a else b
Step-by-Step Solution
Solution:
  1. Step 1: Identify single-expression function syntax

    It must use '=' followed by a single expression without braces.
  2. Step 2: Check each option

    fun max(a: Int, b: Int) = if (a > b) a else b uses '=' with an if-else expression correctly. fun max(a: Int, b: Int) { if (a > b) return a else return b } uses braces and return statements, not single-expression. fun max(a: Int, b: Int): Int { return if (a > b) a else b } uses braces and return, valid but not single-expression. fun max(a: Int, b: Int) = { if (a > b) a else b } uses braces inside '=', which is invalid.
  3. Final Answer:

    fun max(a: Int, b: Int) = if (a > b) a else b -> Option D
  4. Quick Check:

    Single-expression function with if-else expression = fun max(a: Int, b: Int) = if (a > b) a else b [OK]
Quick Trick: Use '=' with if-else expression for single-expression max function [OK]
Common Mistakes:
MISTAKES
  • Using braces and return in single-expression functions
  • Placing expression inside braces after '='
  • Confusing block function with single-expression

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes