In this blog, we are going to see how kotlin lambda expression makes our code more expressive and concise. Recently, I’ve noticed that there are a few different ways to pass a function as a parameter. In this post I will use 2 functions: We have to declare the method, in such a way that it can receive the method as an argument. The most common and often more convenient (according to Kotlin documentation) is to pass a lambda expression.
1. Pass a lambda expression
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sum = calculateSum(12, 5, { divide(8, 2) }) Log.e("SUM", sum.toString()) } private fun calculateSum(a: Int, b: Int, c: () -> Int): Int { return a + b + c() } private fun divide(a: Int, b: Int): Int { return a / b } } |
In the above example, we have passed a lambda expression to calculateSum() method which will return the sum of these variables after execution of divide function. This is how we write lambda expression in a function: Expression_Name(Param1,Param2,Param3)->RetrunType
2. Pass lambda expression directly without passing method
1 2 3 4 5 6 7 8 9 10 11 12 |
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sum =calculateSum(12, 6, { a, b -> a / b }) Log.e("SUM", sum.toString()) } private fun calculateSum(a: Int, b: Int, c: (Int, Int) -> Int): Int { return a + b + c(a, b) } } |
In this 2 example, we have lambda expression directly without passing method itself in the previous example we have passed the divide() function as the parameter. Regular functions receive only data parameters, whereas a function that receives another function as a parameter or returns a function, as a result, is called a Higher-order function. So, our functions that receive a lambda callback are basically higher-order functions.
Hope this blog will give you a basic idea of how we can pass lambda express or function to a method.