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

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.

主站蜘蛛池模板: 大悟县| 东明县| 白城市| 自治县| 克山县| 马公市| 石狮市| 临城县| 永川市| 长海县| 疏勒县| 甘洛县| 西和县| 上杭县| 定陶县| 随州市| 钟山县| 贵州省| 迭部县| 汝州市| 株洲县| 安阳县| 遂溪县| 济宁市| 都昌县| 永川市| 临湘市| 宜城市| 高安市| 平潭县| 阿尔山市| 西城区| 临潭县| 朝阳县| 石林| 防城港市| 伊金霍洛旗| 武乡县| 衡东县| 安徽省| 集贤县|