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

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:

主站蜘蛛池模板: 大邑县| 保亭| 西城区| 辽宁省| 巫溪县| 西城区| 兴安盟| 沂源县| 金溪县| 资中县| 嘉定区| 洪雅县| 梁河县| 高安市| 娄底市| 嘉峪关市| 莱阳市| 潜山县| 济南市| 达拉特旗| 利辛县| 石狮市| 吉林市| 宁安市| 杭锦旗| 中超| 汤阴县| 马山县| 电白县| 韶山市| 吉林市| 甘泉县| 马鞍山市| 乌鲁木齐市| 读书| 万源市| 中西区| 万年县| 庆阳市| 蓬莱市| 绿春县|