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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.126