Menu
Coddy logo textTech

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 * 2

Both 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 == 0

Single-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 icon

Challenge

Medium

Write 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 price
  • percentage (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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground