Kotlin Lambda Function : How to return something ?
A Kotlin lambda function, also known as a lambda expression or anonymous function, is a concise way to define a function without explicitly declaring its name.
It allows you to create a function on-the-fly, typically as an argument to another function or as a way to represent a block of code as a value.
Lambdas are a key feature of functional programming and can make your code more expressive and concise.
In Kotlin, the syntax for a lambda function is as follows
{ arguments -> body }
Here, arguments represent the input parameters of the lambda function, and body represents the code block that is executed when the lambda is invoked.
For example, a simple lambda function that takes two integers and returns their sum
Open Kotlin Playground and write the following program.
fun main() {
val sum = { a:Int, b:Int -> a+b }
print("Sum :${sum(10,34)}")
}
In this case, the lambda function takes two arguments (a and b), and the body of the lambda (a + b) returns their sum. The inferred type of this lambda function would be (Int, Int) -> Int.
Lambda functions are often used with higher-order functions such as map, filter, and reduce, where they can be passed as arguments to perform operations on collections. Here’s an example using the map function.
val numbers = listOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
In this case, the lambda function it * it squares each element of the numbers list using the map function.
Kotlin Lambda Positive Sum Example
fun main() {
val numbers = listOf(-1, 2, -3, 4, -5, 6, -7)
val positiveSum = numbers.filter { it > 0 }.sum()
println("The sum of positive numbers is: $positiveSum")
}
In this example, we have a list of numbers (numbers) that contains both positive and negative values. We use the filter function with a lambda expression ({ it > 0 }) to filter out the positive numbers from the list.
The lambda expression checks if each element (it) is greater than zero. The filter function returns a new list that contains only the positive numbers.
Next, we call the sum function on the filtered list to calculate the sum of the positive numbers. The sum function adds up all the elements in the list and returns the total sum.
Find odd or even number using Lambda function
fun main() {
val oddOrEven = {number: Int ->
if(number%2==0){
println("even")
}else {
println("odd") }
}
oddOrEven(30)
}
Output
even
The code you provided demonstrates the use of a lambda function in Kotlin to determine whether a given number is odd or even.
The code defines a variable oddOrEven and assigns a lambda function to it. The lambda function takes an Int parameter called number.
The lambda function’s body contains an if statement that checks if number is divisible evenly by 2 (i.e., number % 2 == 0). If the condition is true, the lambda prints “even” using println. Otherwise, if the condition is false, it prints “odd”.
After defining the lambda function, the code immediately invokes it by calling oddOrEven(30), passing the number 30 as an argument.
Let’s shorten it
fun main() {
val oddOrEven2 = {number:Int -> if(number%2==0) "even" else "odd" }
println(oddOrEven2(44))
}
Another possible way:
fun main() {
val mult: (Int, Int) -> Int = {a, b -> a * b}
print( mult(5,10))
}
Output : 50
The code declares a variable named mult with the type (Int, Int) -> Int. This type represents a function that takes two Int parameters and returns an Int.
The right-hand side of the assignment = { a, b -> a * b } defines the lambda function. The lambda takes two parameters a and b, and its body multiplies them together using the * operator.
he print function is called with mult(5, 10) as its argument. This invokes the lambda function assigned to mult with arguments 5 and 10.
fun main() {
val item = listOf("o","u","j")
val show = { a:List<String> -> println(a) }
show(item)
}
The code declares a variable named item and initializes it with a list of strings: listOf(“o”, “u”, “j”).
The code declares a variable named show and assigns a lambda function to it. The lambda function takes a single parameter a of type List, representing a list of strings.
The body of the lambda function consists of a single statement println(a), which prints the contents of the list a.
The show variable is then invoked as a function with the item list as an argument using show(item).
Output : [o, u, j]
Repeat using Lambda
fun main() {
val frutis = listOf("Apple","Orange","Pine apple","green apple")
val rp = {
list:List<String> -> println("$frutis \n".repeat(4))
}
rp(frutis)
}
[Apple, Orange, Pine apple, green apple]
[Apple, Orange, Pine apple, green apple]
[Apple, Orange, Pine apple, green apple]
[Apple, Orange, Pine apple, green apple]