简体   繁体   中英

Trying to understand Kotlin Example

I want to learn Kotlin and am working through the Examples on try.kotlinlang.org

I have trouble understanding some examples, particularly the Lazy property example: https://try.kotlinlang.org/#/Examples/Delegated%20properties/Lazy%20property/Lazy%20property.kt

/**
 * Delegates.lazy() is a function that returns a delegate that implements a lazy property:
 * the first call to get() executes the lambda expression passed to lazy() as an argument
 * and remembers the result, subsequent calls to get() simply return the remembered result.
 * If you want thread safety, use blockingLazy() instead: it guarantees that the values will
 * be computed only in one thread, and that all threads will see the same value.
 */

class LazySample {
    val lazy: String by lazy {
        println("computed!")
        "my lazy"
    }
}

fun main(args: Array<String>) {
    val sample = LazySample()
    println("lazy = ${sample.lazy}")
    println("lazy = ${sample.lazy}")
}

Output:

computed!
lazy = my lazy
lazy = my lazy

I don't get what is happening here. (probably because I am not really familiar with lambdas)

  • Why is the println() only executed once?

  • I am also confused about the line "my lazy" the String isn't assigned to anything (String x = "my lazy") or used in a return (return "my lazy)

Can someone explain please? :)

Why is the println() only executed once?

That happens because the first time you are accessing to it, it is created. To be created, it invokes the lambda that you passed only one time and assigns the value "my lazy" . The code you wrote in Kotlin is the same of this java code:

public class LazySample {

    private String lazy;

    private String getLazy() {
        if (lazy == null) {
            System.out.println("computed!");
            lazy = "my lazy";
        }
        return lazy;
    }
}

I am also confused about the line "my lazy" the String isn't assigned to anything (String x = "my lazy") or used in a return (return "my lazy)

Kotlin supports implicit returns for lambda. It means that the last statement of a lambda is considered its return value. You can also specify an explicit return with return@label . In this case:

class LazySample {
    val lazy: String by lazy {
        println("computed!")
        return@lazy "my lazy"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM