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:
Step 1: Identify single-expression function syntax
It must use '=' followed by a single expression without braces.
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.
Final Answer:
fun max(a: Int, b: Int) = if (a > b) a else b -> Option D
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
Master "Functions" in Kotlin
9 interactive learning modes - each teaches the same concept differently