2017-10-04 86 views
1

我想學習科特林和我通過實例對工作 try.kotlinlang.org試圖瞭解科特林例

我聽不太懂一些例子,特別是懶惰的屬性例如: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}") 
} 

輸出:

computed! 
lazy = my lazy 
lazy = my lazy 

我不明白這裏發生了什麼。 (可能是因爲我不熟悉lambda)

  • 爲什麼println()只執行一次?

  • 我也困惑行「我懶」 字符串沒有分配到任何東西(串x =「我的懶惰」),或在返回 使用(返回「我的懶惰)

有人能解釋嗎?:)

回答

5

爲什麼的println()只執行一次?

那天正好BEC當您第一次訪問它時,會創建它。要創建它,它會調用您只傳遞一次的lambda,並指定值"my lazy"。 你Kotlin寫的代碼是一樣的這段Java代碼:

public class LazySample { 

    private String lazy; 

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

我也困惑行「我懶」的字符串沒有被分配 任何東西(串x =「我懶惰「),或在返回用(返回」我 懶惰)

科特林支持implicit returns的拉姆達。這意味着一個lambda的最後一條語句被認爲是它的返回值。 你也可以指定一個明確的回報與[email protected]。 在這種情況下:

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