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

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:

主站蜘蛛池模板: 梧州市| 九台市| 霍州市| 东台市| 莎车县| 安新县| 新民市| 天祝| 海城市| 遂昌县| 高州市| 乃东县| 惠东县| 赣州市| 万州区| 湘乡市| 时尚| 临澧县| 莱西市| 波密县| 南城县| 永州市| 山阳县| 全南县| 嘉禾县| 阜阳市| 西城区| 新野县| 洞头县| 沧源| 许昌市| 大连市| 晋州市| 武威市| 体育| 墨江| 元朗区| 理塘县| 安庆市| 北票市| 静乐县|