Skip to main content

Kotlin Single Expression Functions

In Kotlin, writing concise and readable code is a priority. One feature that helps achieve this goal is single expression functions - a way to define functions in a more compact form when they consist of just one expression.

What are Single Expression Functions?​

Single expression functions are functions that return the result of a single expression. Instead of using curly braces {} and an explicit return statement, you can simply use the assignment operator (=) followed by the expression.

Basic Syntax​

The syntax for single expression functions is:

kotlin
fun functionName(parameters): ReturnType = expression

Regular Functions vs. Single Expression Functions​

Let's compare the traditional function syntax with single expression functions:

Traditional Function​

kotlin
fun add(a: Int, b: Int): Int {
return a + b
}

Single Expression Function​

kotlin
fun add(a: Int, b: Int): Int = a + b

Both functions do exactly the same thing, but the single expression version is more concise.

Type Inference in Single Expression Functions​

Kotlin's type inference works particularly well with single expression functions. You can often omit the return type:

kotlin
fun add(a: Int, b: Int) = a + b

The Kotlin compiler can infer that this function returns an Int based on the expression on the right-hand side.

However, it's often considered good practice to include return types for public functions to make the API more self-documenting.

Examples of Single Expression Functions​

Example 1: Simple Calculations​

kotlin
fun square(number: Int) = number * number

// Usage:
fun main() {
val result = square(5)
println("Square of 5 is $result") // Output: Square of 5 is 25
}

Example 2: String Operations​

kotlin
fun greet(name: String) = "Hello, $name!"

// Usage:
fun main() {
val greeting = greet("Kotlin")
println(greeting) // Output: Hello, Kotlin!
}

Example 3: Boolean Checks​

kotlin
fun isEven(number: Int) = number % 2 == 0

// Usage:
fun main() {
println("Is 4 even? ${isEven(4)}") // Output: Is 4 even? true
println("Is 7 even? ${isEven(7)}") // Output: Is 7 even? false
}

When to Use Single Expression Functions​

Single expression functions are ideal for:

  1. Simple operations: When your function performs one simple operation
  2. Transformations: Converting one value to another
  3. Predicates: Functions that return boolean results
  4. Delegate functions: Functions that simply call another function

When Not to Use Single Expression Functions​

Single expression functions might not be appropriate when:

  1. The logic is complex: If the expression becomes too long or complex
  2. Multiple operations are needed that can't be combined into a single expression
  3. Debugging is required (it's harder to set breakpoints within single expressions)

Real-World Applications​

Example: Data Processing​

kotlin
// Converting a database entity to a UI model
fun convertUserToViewModel(user: User) = UserViewModel(
id = user.id,
displayName = "${user.firstName} ${user.lastName}",
isActive = user.status == "ACTIVE"
)

// Usage in an app
fun displayUserInfo(userId: String) {
val user = fetchUserFromDatabase(userId)
val viewModel = convertUserToViewModel(user)
renderUserInterface(viewModel)
}

Example: Math Utilities​

kotlin
fun calculateCircleArea(radius: Double) = Math.PI * radius * radius

// Usage:
fun main() {
val radius = 5.0
val area = calculateCircleArea(radius)
println("Area of circle with radius $radius is $area")
// Output: Area of circle with radius 5.0 is 78.53981633974483
}

Example: Functional Programming​

Single expression functions work well in functional programming paradigms:

kotlin
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)

// Using single expression functions with higher-order functions
val doubled = numbers.map { it * 2 }
val filtered = numbers.filter { it % 2 == 0 }

println("Doubled: $doubled") // Output: Doubled: [2, 4, 6, 8, 10, 12]
println("Even numbers: $filtered") // Output: Even numbers: [2, 4, 6]
}

Making Complex Logic Work in Single Expression Functions​

Sometimes you can use Kotlin's powerful features to make more complex logic fit into a single expression:

Using if-else as an Expression​

kotlin
fun max(a: Int, b: Int) = if (a > b) a else b

// Usage:
fun main() {
println("Maximum of 5 and 3 is ${max(5, 3)}") // Output: Maximum of 5 and 3 is 5
}

Using when as an Expression​

kotlin
fun describe(number: Int) = when {
number < 0 -> "Negative"
number == 0 -> "Zero"
number % 2 == 0 -> "Positive even"
else -> "Positive odd"
}

// Usage:
fun main() {
println(describe(-5)) // Output: Negative
println(describe(0)) // Output: Zero
println(describe(4)) // Output: Positive even
println(describe(7)) // Output: Positive odd
}

Using try-catch as an Expression​

kotlin
fun parseIntSafely(s: String) = try {
s.toInt()
} catch (e: NumberFormatException) {
null
}

// Usage:
fun main() {
println(parseIntSafely("123")) // Output: 123
println(parseIntSafely("abc")) // Output: null
}

Summary​

Kotlin single expression functions allow you to write concise, readable code by eliminating boilerplate when a function consists of just one expression. They are particularly useful for simple operations, transformations, and predicates.

Key benefits include:

  • Reduced verbosity: Less code to write and maintain
  • Improved readability: The function's purpose is often clearer
  • Type inference: Return type can often be inferred by the compiler
  • Functional style: Encourages a more functional programming approach

As you develop your Kotlin programming skills, single expression functions will become a natural part of your coding style, helping you write more elegant code.

Additional Resources​

Exercises​

  1. Convert these regular functions to single expression functions:

    kotlin
    fun multiply(a: Int, b: Int): Int {
    return a * b
    }

    fun capitalize(text: String): String {
    return text.uppercase()
    }
  2. Create a single expression function called isAdult that checks if a given age is 18 or above.

  3. Write a single expression function that returns the absolute value of a number without using the standard library's abs function.

  4. Create a single expression function that formats a person's full name given their first and last names.



If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)