- 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.
- Web程序設(shè)計及應(yīng)用
- Java程序設(shè)計與開發(fā)
- 深度學(xué)習(xí)經(jīng)典案例解析:基于MATLAB
- Java 9 Programming Blueprints
- 編寫高質(zhì)量代碼:改善C程序代碼的125個建議
- Python算法從菜鳥到達人
- The DevOps 2.5 Toolkit
- PHP從入門到精通(第4版)(軟件開發(fā)視頻大講堂)
- Modular Programming with JavaScript
- 例說FPGA:可直接用于工程項目的第一手經(jīng)驗
- Python深度學(xué)習(xí)(第2版)
- HTML5程序設(shè)計基礎(chǔ)教程
- 你也能看得懂的Python算法書
- 寫給所有人的編程思維
- 匯編語言程序設(shè)計教程