Kotlin Lambda
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
We can use lambda expressions to create a shortened function in Kotlin. It is a type anonymous function.
Lambda syntax is
val lambdaname = {arg1 -> expression, ... argn -> expression}
Example of a lambda in Kotlin
In the following example, we created a lambda expression to print a Hi message, and we used that to print a couple of messages.
fun main(args: Array<String>)
{
val sayHi = { x: String -> print("Hi $x\n")}
sayHi("Mugambo!")
sayHi("Kush Hua!")
}
Output:
Hi Mugambo!
Hi Kush Hua!
Lambda Expressions in filter
Let us see another example of lambda in action. Let's say I have an Array of country names.
I only want those countries which start with U.
We can use filter function in Array with lambda as given below.
fun main(args: Array<String>)
{
var countryNames: List<String> = arrayListOf("United States", "United Kingdom", "India")
println("Before Filter: ")
println(countryNames)
var countryNamesFilter: List<String> = countryNames.filter { s -> s.startsWith("U") }
println("After Filter: ")
println(countryNamesFilter)
}
Output:
Before Filter:
[United States, United Kingdom, India]
After Filter:
[United States, United Kingdom]