Kotlin Functions : Single Expression, Named, Default
One of the key features that makes Kotlin stand out is its robust function system.We will delve into the world of Kotlin functions, exploring their versatility and flexibility.
How to define a Kotlin Function
Kotlin provides a clean and straightforward syntax for defining functions. Instead of the traditional “void” return type in Java, Kotlin requires explicit specification of the return type using a colon after the function name.
fun calculateSum(a: Int, b: Int): Int {
return a + b
}
Open Kotlin Playground write the following code:
fun main() {
println("Sum : ${calculate(5,105)}")
}
fun calculate(a: Int, b: Int): Int
{
return a+b
}
Sum : 110
In the main function, the program prints the sum of two numbers using the calculate function. The expression “Sum : ${calculate(5,105)}” is passed as an argument to the println function to display the result.
The values 5 and 105 are the arguments passed to the calculate function.
The calculate function is defined below the main function. It takes two parameters, a and b, both of type Int, and returns an Int. Inside the function, the sum of a and b is calculated using the + operator, and the result is returned.
When the program is executed, the main function is automatically called, and the result of the calculate function is printed as “Sum : [Result]”. In this case, the sum of 5 and 105 is 110, so the output would be “Sum : 110”.
Kotlin Single Expression Functions
Kotlin’s concise nature allows for single-expression functions, where the function body is reduced to a single expression.
In such cases, the return type can be inferred by the compiler, further reducing boilerplate code.
fun calculateSum(a: Int, b: Int) = a + b
main.kt
fun main() {
println("Sum : ${calculateSum(5,105)}")
}
fun calculateSum(a: Int, b: Int) = a + b
Output
Sum : 110
The above function ‘calculateSum’ automatically returns the sum of two integers.
Kotlin Default Arguments
Kotlin functions support default argument values, which enable the specification of default values for function parameters.This feature simplifies function calls by allowing developers to omit arguments with default values.
Default Argument Example
fun greet(name: String, message: String = "Hello") {
println("$message, $name!")
}
fun main()
{
greet("Nikin") // Output: Hello, Nikin!
greet("Yoko", "Hi") // Output: Hi, Yoko!
}
Hello, Nikin!
Hi, Yoko!
In the above code snippet, the second parameter has a default value of “Hello,” making it optional in function calls.
Named Arguments in Kotlin
Kotlin allows the use of named arguments, which allows developers to specify function arguments by their parameter names, regardless of their order.
This feature enhances code readability and helps avoid confusion when dealing with functions with multiple parameters.
fun createPerson(name: String, age: Int, city: String) {
println("Name: $name\n Age: $age \n City: $city")
}
fun main()
{
createPerson(name = "Nikki", city = "Kochi", age = 39)
}
Name: Nikki
Age: 39
City: Kochi
Using named arguments makes the intent of the function call clearer, especially when dealing with functions that have similar parameter types.
Kotlin Higher-Order Functions
Kotlin supports higher-order functions, This means functions can be passed as arguments, returned from other functions, or stored in variables.
Higher-order functions enable powerful abstractions and functional programming paradigms, making code more expressive and concise.
fun performOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
fun main()
{
val sum: (Int, Int) -> Int = { x, y -> x + y }
val result = performOperation(5, 10, sum)
println(result)
}
Output
15
In the above code, the performOperation function takes two integers and a higher-order function operation as arguments.
The sum function, defined separately, is passed as an argument to calculate the sum of the two integers.
Read more about Kotlin Lambda functions
whether you’re a Kotlin beginner or a seasoned developer, make the most of Kotlin functions and unlock their true potential in your next project. Happy coding!