Kotlin我爱编程

Kotlin with run let 用法

2018-07-24  本文已影响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")
}
上一篇 下一篇

猜你喜欢

热点阅读