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

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.

主站蜘蛛池模板: 大宁县| 澎湖县| 中阳县| 永州市| 大姚县| 常州市| 昭通市| 盘锦市| 乡城县| 聂拉木县| 射阳县| 星子县| 孝义市| 吉木乃县| 江北区| 祁阳县| 上饶市| 湖口县| 桦南县| 拉萨市| 宝鸡市| 道孚县| 邵东县| 庐江县| 友谊县| 尚志市| 汽车| 霸州市| 察哈| 浦县| 宝清县| 措勤县| 汉寿县| 宁强县| 遵化市| 方城县| 房产| 毕节市| 建湖县| 永顺县| 花莲市|