- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 208字
- 2021-06-24 19:15:26
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.
- Oracle從入門到精通(第3版)
- Mastering Entity Framework Core 2.0
- Boost C++ Application Development Cookbook(Second Edition)
- arc42 by Example
- TestNG Beginner's Guide
- Scratch 3.0少兒編程與邏輯思維訓練
- Lua程序設計(第4版)
- Magento 1.8 Development Cookbook
- Visual C++應用開發
- Learning jQuery(Fourth Edition)
- 軟件供應鏈安全:源代碼缺陷實例剖析
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- Building Web and Mobile ArcGIS Server Applications with JavaScript(Second Edition)
- 鋁合金陽極氧化與表面處理技術(第三版)
- Neo4j權威指南 (圖數據庫技術叢書)