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

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:

主站蜘蛛池模板: 吉首市| 松原市| 广安市| 淮安市| 武汉市| 电白县| 临颍县| 南阳市| 南涧| 澄城县| 巴彦县| 油尖旺区| 安西县| 清水县| 衡阳县| 红原县| 崇仁县| 伊通| 邹平县| 阿图什市| 威远县| 尚义县| 凌源市| 松溪县| 谢通门县| 息烽县| 出国| 马龙县| 健康| 乌兰县| 金昌市| 治多县| 碌曲县| 洛浦县| 安图县| 余姚市| 厦门市| 七台河市| 海安县| 油尖旺区| 柳林县|