- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 263字
- 2021-06-10 18:49:21
Lambda expressions in Kotlin
Functional programming can be advantageous when we are performing lots of different operations on data that has a known, fixed amount of variation. It provides a very elegant way to write code with immutability. It also allows you to write pure functions.
A lambda expression is an anonymous function that represents the implementation of single abstract method (SAM) of an interface. Lambda expressions deal with expressions and promote immutability, which turn functions into higher-order functions.
Let's write a lambda expression. Consider the following code for 12_LambdaExpressions_HelloWorld.kts:
val greetingLambda = { println("Hello from Lambda")}
greetingLambda()
The output is as follows:
We can invoke lambda functions directly, as in the example shown in the preceding code, or we can use invoke() as follows—greetingLambda.invoke():
val greetingLambda = { println("Hello from Lambda")}
greetingLambda.invoke()
In the next example, we will write a lambda expression that takes an argument. Consider the following code for 12a_LambdaExpressions.kts:
val greetingLambda = { user: String -> println("Hello ${user}")}
greetingLambda.invoke("Tom")
The output is as follows:
We will now write an inline lambda function to print only even numbers. Consider the following code for 12b_LambdaExpressions.kts:
listOf(0,1,2,3,4,5,6,7,8,9)
.filter{ e -> e % 2 == 0}
.forEach{ e -> println(e)}
Here, we created a list of numbers from 0-9, and then we used filter to retrieve only the even numbers. Finally, we used forEach to iterate over the numbers and print the values to the console.
The output of the preceding code is as follows:
- Learn TypeScript 3 by Building Web Applications
- 深入理解Django:框架內(nèi)幕與實(shí)現(xiàn)原理
- Practical Internet of Things Security
- C# 從入門(mén)到項(xiàng)目實(shí)踐(超值版)
- Visual Basic程序設(shè)計(jì)(第3版):學(xué)習(xí)指導(dǎo)與練習(xí)
- Scala編程實(shí)戰(zhàn)(原書(shū)第2版)
- 軟件測(cè)試技術(shù)指南
- Kotlin從基礎(chǔ)到實(shí)戰(zhàn)
- 從零開(kāi)始學(xué)C語(yǔ)言
- NGINX Cookbook
- jQuery炫酷應(yīng)用實(shí)例集錦
- Multithreading in C# 5.0 Cookbook
- Kotlin Programming By Example
- Arduino Wearable Projects
- Scala Functional Programming Patterns