官术网_书友最值得收藏!

Functional paradigms

Kotlin supports a functional style of programming that allows you to write more elegant, concise, and expressive code.

In Kotlin, we don't have to write lengthy code to provide simple functionality. Pure functions and higher-order functions avoid mutating the states, thereby reducing the complexity of the code and improving its readability.

Lambda expressions are anonymous functions that represent the implementation of a Single Abstract Method(SAM) interface. We can pass lambda expressions to functions. In doing this, we are not passing objects, but instead we are passing behaviors to the functions that are evaluated without mutating the state of an object. This turns a function into a higher-order function.

Consider the following lambda expression:

val greetingLambda = { println("Greet from inline lambda") }

This can be invoked using the following:

greetingLambda() or

greetingLambda.invoke()

The output of the preceding lambda expression is as follows:

Let's write an inline lambda expression to print even numbers:

listOf(0,1,2,3,4,5,6,7,8,9)
.filter{ e -> e % 2 == 0}
.forEach{ e -> println(e)}

The output will be as follows:

主站蜘蛛池模板: 黔西县| 闻喜县| 栖霞市| 清丰县| 洛隆县| 永和县| 万山特区| 霍林郭勒市| 阳春市| 新和县| 襄樊市| 玉环县| 通海县| 梓潼县| 云梦县| 盐亭县| 玛沁县| 农安县| 广东省| 阆中市| 元谋县| 五台县| 确山县| 渝北区| 和政县| 伊吾县| 文山县| 临猗县| 玉龙| 崇仁县| 长春市| 客服| 松滋市| 辰溪县| 洪湖市| 石屏县| 建瓯市| 玛沁县| 榕江县| 井冈山市| 葫芦岛市|