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

Lazy evaluation

Some functional languages provide a lazy (non-strict) evaluation mode. Kotlin, by default, uses an eager (strict) evaluation.

Kotlin doesn't provide native support for lazy evaluation as part of the language itself, but as part of Kotlin's Standard Library and a language feature named delegate properties (we'll cover this in detail in future chapters):

fun main(args: Array<String>) {
val i by lazy {
println("Lazy evaluation")
1
}

println("before using i")
println(i)
}

The output will look something like the following screenshot:

After the by reserved word, the lazy() higher-function receives an (() -> T) initializer lambda function that will be executed the first time that i is accessed.

But also a normal lambda function can be used for some lazy use cases:

fun main(args: Array<String>) {
val size = listOf(2 + 1, 3 * 2, 1 / 0, 5 - 4).size
}

If we try to execute this expression, it will throw an ArithmeticException exception, as we are dividing by zero:

fun main(args: Array<String>) {
val size = listOf({ 2 + 1 }, { 3 * 2 }, { 1 / 0 }, { 5 - 4 }).size
}

There's no problem executing this. The offending code isn't being executed, effectively making it a lazy evaluation.

主站蜘蛛池模板: 石嘴山市| 化州市| 昌宁县| 大洼县| 南靖县| 鄂尔多斯市| 南雄市| 建湖县| 黑龙江省| 石家庄市| 历史| 香港 | 丰顺县| 英山县| 丹阳市| 武义县| 通化县| 会理县| 瑞安市| 五家渠市| 孝义市| 武冈市| 承德县| 中江县| 喀什市| 关岭| 维西| 张掖市| 呼图壁县| 抚顺市| 湘潭市| 新疆| 乌鲁木齐县| 五河县| 武鸣县| 水城县| 金塔县| 冕宁县| 武城县| 桃源县| 南宁市|