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

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:

主站蜘蛛池模板: 华宁县| 民乐县| 承德市| 丁青县| 兴和县| 乌拉特前旗| 北海市| 阳西县| 阳江市| 仙游县| 方城县| 昌乐县| 石城县| 阿鲁科尔沁旗| 巫山县| 德保县| 象山县| 霍州市| 石阡县| 永修县| 尉犁县| 神木县| 鹰潭市| 岳池县| 建湖县| 纳雍县| 酒泉市| 安康市| 临汾市| 华蓥市| 惠东县| 东乌| 拜泉县| 金坛市| 西平县| 韶山市| 禹州市| 安岳县| 宜宾市| 盐边县| 合川市|