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

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:

主站蜘蛛池模板: 博乐市| 瑞昌市| 广宁县| 故城县| 沙湾县| 邛崃市| 昌平区| 云林县| 余姚市| 公主岭市| 慈利县| 越西县| 随州市| 孟村| 曲松县| 揭东县| 竹北市| 喜德县| 黑河市| 进贤县| 五指山市| 磴口县| 灵台县| 桓仁| 濮阳市| 台北市| 兴宁市| 巨鹿县| 绥棱县| 延吉市| 家居| 上饶县| 吉木萨尔县| 永和县| 双城市| 凤翔县| 梨树县| 静安区| 贵州省| 临海市| 揭阳市|