Functions in Kotlin
In Kotlin, functions are fundamental building blocks used to organize and structure code. They encapsulate a set of instructions that perform a specific task or calculation. Here's an explanation of functions in Kotlin along with an example to illustrate their usage:
Declaring Functions
Functions in Kotlin are declared using the fun keyword followed by the function name, parameters (if any), return type, and function body enclosed in curly braces {}. Here's a basic syntax.
fun functionName(parameter1: Type1, parameter2: Type2, ...): ReturnType {
// body of the function
}
Let's create a simple Kotlin function that calculates the sum of two integers and returns the result.
fun sum(a: Int, b: Int): Int {
return a + b
}
Lambda Functions (Anonymous Functions)
Kotlin also supports lambda functions, which are unnamed functions that can be used as expressions. A function without a name is called an anonymous function. For lambda expression, we can say that it is an anonymous function. Lambda functions are particularly useful when you need to define a simple function without explicitly declaring a named function.
Syntax of Lambda Functions
The general syntax of a lambda function in Kotlin is.
{ parameters ->
body
}
Below is an example of a lambda function to add two integers.
Create a kotlin file lambda.kt
fun main() {
val lambda: (Int, Int) -> Int = { x, y -> x + y }
val result = lambda(5, 10)
println(result)
}
Output
15
HigherOrder Function
In Kotlin, higher-order functions are functions that can accept other functions as parameters or return functions. This concept is closely related to functional programming principles and allows for powerful and flexible code structures. Here's a detailed explanation of higher-order functions in Kotlin.
Accepting Functions as Parameters
In Kotlin, functions can be passed as parameters to other functions. This is useful when you want to encapsulate a piece of functionality that can vary (like different ways of processing data) and pass it to another function for execution. Here's a basic example:
below is an example of a Higher-order function to add two double values
Create a Kotlin file HighOrder.kt
fun add(a: Double, b: Double): Double {
return a + b
}
fun highOrder(x: Double, y: Double, fn: (Double, Double) -> Double) {
print(fn(x, y))
}
fun main() {
highOrder(5.0, 6.5, ::add) // passing function as a parameter
}
Output
11.5