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:
fun functionName(parameters): ReturnType = expression
Regular Functions vs. Single Expression Functions
Let's compare the traditional function syntax with single expression functions:
Traditional Function
fun add(a: Int, b: Int): Int {
return a + b
}
Single Expression Function
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:
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
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
fun greet(name: String) = "Hello, $name!"
// Usage:
fun main() {
val greeting = greet("Kotlin")
println(greeting) // Output: Hello, Kotlin!
}
Example 3: Boolean Checks
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:
- Simple operations: When your function performs one simple operation
- Transformations: Converting one value to another
- Predicates: Functions that return boolean results
- Delegate functions: Functions that simply call another function
When Not to Use Single Expression Functions
Single expression functions might not be appropriate when:
- The logic is complex: If the expression becomes too long or complex
- Multiple operations are needed that can't be combined into a single expression
- Debugging is required (it's harder to set breakpoints within single expressions)
Real-World Applications
Example: Data Processing
// 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
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:
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
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
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
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
-
Convert these regular functions to single expression functions:
kotlinfun multiply(a: Int, b: Int): Int {
return a * b
}
fun capitalize(text: String): String {
return text.uppercase()
} -
Create a single expression function called
isAdult
that checks if a given age is 18 or above. -
Write a single expression function that returns the absolute value of a number without using the standard library's
abs
function. -
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 [email protected]. I’d greatly appreciate your feedback! :)