Updated April 6, 2023
Introduction to Kotlin lambda
The kotlin lambda is defined as the function, and it is one of the expressions; it is also called an anonymous function. It may be treated as the function literals, which means it is not declared but is passed immediately as the expression. The custom actions are also used to validate the user data on the backend logic. The lambda expression is passed as the parameter, and it is stored as a separate variable, and it returns the value the parameters are passed on the left side of the arrow, and the actual code is passed on the right side of the arrow.
Syntax
The kotlin language uses a number of variables, keywords, operators, and methods to create the application. Like the lambda function is one of the anonymous functions, it can be denoted as the -> arrow symbol.
fun main(args:Array<String>)
{
val eg -> body of function
method()
}
function method(eg: (data type casting if needed)-> variable name)
{
----some logic codes depends upon the requirement---
}
The above codes are the basic syntax for utilizing the lambda function like the arrow -> operator used on the kotlin functions. It is used as the code redundancy, and it has more performance.
How does the lambda function work in Kotlin?
The lambda function is the anonymous function, so it does not have a name to call and utilize the function on the kotlin language. The lambda expression is generated and assigned as a separate variable, and also the expression does not have parameters, and it does not return any value in the function. It also supports the functional programming concept so that they function as arguments while passed to the other functions. Meanwhile, it can be returned the function from the other functions that function are called the higher-order functions.
The lambda expressions are most probably called the higher-order function if we use an empty parenthesis that can be passed as the anonymous function and does not have any specific parameters. And also, lambdas are frequently used while we are working with the collections because it has n number of in-built methods available in the standard library format, so the lambdas are to make our task an easier way. Meanwhile, the lambdas are accepted more than one parameter, so based on the default methods used on the kotlin language, it accomplishes the task with the other library functions, and it returns the value based on the method and its return type.
Examples of Kotlin lambda
Different examples are given below:
Example #1
Code:
package one;
import java.util.Arrays
data class example(val user: String, val ID: Int, val city: String)
fun main(args: Array<String>) {
println("Welcome To My Domain its a first example for regarding the lambda function")
val demo = listOf(
example("first user", 1, "your location is chennai"),
example("second user", 2, "your location is tiruppur"),
example("third user", 3, "your location is mumbai"),
example("fourth user", 4, "your location is andhra"),
example("fifth user", 5, "your location is jammu"),
example("sixth user", 6, "your location is kahmir"),
example("seventh user", 7, "your location is madurai"),
example("eigth user",8, "your location is karnataka"),
example("ninth user", 9, "your location is delhi"),
example("tenth user", 10, "your location is west bengal"),
)
val demo1 = demo
.filter { it.user.startsWith("f") }
.maxBy{ it.ID }
println(demo1)
println("Your input user lists are : ${demo1?.user}" )
println("The user IDs are shown: ${demo1?.ID}" )
println("city: ${demo1?.city}" )
println("Thank you users for spenting the time with our application kindly try and spent more with our application its useful for your knowledge")
}
Output:
The above example used lambda expression with some basic attribute column like user name, ID, and city details to be stored and retrieved. We can also add the two additional methods like a filter for filter out the specific data and the maxBy() method for fetching the maximum of the user id.
Example #2
Code:
package one;
import java.util.Arrays;
val eg = fun(a: Int, b: Int): Int = a + b
val eg1 = fun(a: Int, b: Int): Int {
val resultmul = a * b
return resultmul
}
val eg2 = fun(a: Int, b: Int): Int = a - b
fun main(args: Array<String>){
val demo: (Int) -> Unit= {s: Int -> println(s) }
val sum = eg(7,9)
val resultmul = eg1(7,9)
val minus = eg2(7,9)
println("Thank you users the sum of two numbers is: $sum")
println("Thank you users the multiply of two numbers is: $resultmul")
println("Thank you users the subtraction of two numbers is: $minus")
val new = { println("Thank you for using the lambda concepts in the application!")}
new()
new.invoke()
val new1 = arrayOf(17,7,9)
new1.forEach { unknown -> println(unknown * unknown) }
new1.forEach { println(it*it) }
}
fun demo1(a: Int, b: Int, demo: (Int) -> Unit ){
val add = a + b
demo(add)
}
fun demo2(a: Int, b: Int, demo: (Int) -> Unit ){
val sub = a - b
demo(sub)
}
Output:
In Second Example, we can perform the arithmetic operations by using the lambda expression. Also, we used to invoke() method to invoke and extend any type of class.
Example #3
Code:
package one;
import java.util.Arrays;
import java.util.ArrayList;
fun main(args: Array<String>){
val Employees = ArrayList<String>()
Employees.add("Employee ID")
Employees.add("Employee Name")
Employees.add("Employee Designation")
Employees.add("Employee Department")
Employees.add("Employee Address")
Employees.add("Employee Mobile")
Employees.add("Employee Email")
Employees.forEach{ ex ->
println(ex + ", ")
}
val EmployeeDetails = arrayListOf("1","Siva", "Software Engineer", "IT-Software", "Flat1c, Sathyamoorthy street, srinivasa nagar, tambaram, chennai","8220244056","[email protected]")
val EmployeeDetails1 = arrayListOf("2","Raman", "Software Support Engineer", "IT-Software", "flat43, aravind street, sathyamoorthy nagar, tambaram, chennai","7253287367","[email protected]")
println("Your Company Employee details are: " +EmployeeDetails +EmployeeDetails1)
}
Output:
In the final example, we used the lambda expression for fetching the Employee details using the Array list collection. We can add n number of records for storing and retrieving the datas.
Conclusion
We can see the lambdas for specified the code with n number of things, and it achieved the things that can be impossible with other languages. Mainly in the Android type of application, this concept will help reduce the code lines and debug it easily and memory-wise less when compared to other options.
Recommended Articles
This is a guide to Kotlin lambda. Here we discuss the introduction, syntax, and working of the lambda function in Kotlin along with the examples and outputs. You may also have a look at the following articles to learn more –