- 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.
- Dependency Injection in .NET Core 2.0
- Learning AWS Lumberyard Game Development
- TypeScript圖形渲染實戰:基于WebGL的3D架構與實現
- Spring Boot企業級項目開發實戰
- Hands-On Natural Language Processing with Python
- 用戶體驗增長:數字化·智能化·綠色化
- Android底層接口與驅動開發技術詳解
- 精通MATLAB(第3版)
- RabbitMQ Essentials
- 人工智能算法(卷1):基礎算法
- 深度實踐KVM:核心技術、管理運維、性能優化與項目實施
- Hacking Android
- Learning Kotlin by building Android Applications
- Python編程入門(第3版)
- 啊哈C語言?。哼壿嫷奶魬穑ㄐ抻啺妫?/a>