Single Expression Functions
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 60 of 93.
When a function contains just a single expression, Kotlin offers a more concise syntax. Instead of using curly braces and the return keyword, you can use an equals sign followed by the expression directly.
Here's a regular function compared to its single-expression equivalent:
// Regular function
fun double(n: Int): Int {
return n * 2
}
// Single-expression function
fun double(n: Int): Int = n * 2Both versions work identically, but the second is shorter and easier to read for simple operations.
Kotlin can even infer the return type for single-expression functions, letting you omit it entirely:
fun double(n: Int) = n * 2
fun greet(name: String) = "Hello, $name!"This syntax works beautifully with conditional expressions too:
fun max(a: Int, b: Int) = if (a > b) a else b
fun isEven(n: Int) = n % 2 == 0Single-expression functions are ideal for simple calculations, validations, and transformations. They keep your code clean and focused on what the function does rather than the mechanics of returning a value.
Challenge
MediumWrite a function calculateDiscount that takes price and percentage and returns the discounted price.
Use the single-expression function syntax (with = instead of curly braces and return) to calculate the final price after applying the discount.
The discounted price is calculated as: price - (price * percentage / 100)
Parameters:
price(Double): The original pricepercentage(Int): The discount percentage (0-100)
Returns: The price after applying the discount (Double)
Try it yourself
fun calculateDiscount(price: Double, percentage: Int): Double {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground