美文网首页Kotlin我爱编程
Kotlin with run let 用法

Kotlin with run let 用法

作者: 假装在去天使之城的路上 | 来源:发表于2018-07-24 13:56 被阅读47次

    下面这种情况,两个是做同一件事情。

    with(webview.settings) {
        javaScriptEnabled = true
        databaseEnabled = true
    }
    // similarly
    webview.settings.run {
        javaScriptEnabled = true
        databaseEnabled = true
    }
    
    

    但是,在需要辨别null的情况下:

    // Yack!
    with(webview.settings) {
          this?.javaScriptEnabled = true
          this?.databaseEnabled = true
       }
    }
    // Nice.
    webview.settings?.run {
        javaScriptEnabled = true
        databaseEnabled = true
    }
    

    T.run 和 T.let 接受变量不同

    stringVariable?.run {
          println("The length of this String is $length")
    }
    // Similarly.
    stringVariable?.let {
          println("The length of this String is ${it.length}")
    }
    

    T.run is just using made as extension function calling block: T.()
    T.let is sending itself into the function i.e. block: (T).

    The T.let allow better naming of the converted used variable i.e. you could convert it to some other name.

    stringVariable?.let {
          nonNullString ->
          println("The non null string is $nonNullString")
    }
    

    相关文章

      网友评论

        本文标题:Kotlin with run let 用法

        本文链接:https://www.haomeiwen.com/subject/zywemftx.html