kotlin標準庫擴展之 let run apply also(一)

  • 2019 年 10 月 4 日
  • 筆記

kotlin十分簡便系統為我們提供了一些十分簡便的標準庫擴展,今天我們就看看這些常規的使用頻率比較高的能幫助我們加速開發的標準庫吧

let

對於學習Kotlin這門語言的人來說肯定都知道其一個特點—安全,添加了null的數據類型比如var a? = null 那麼現實開發中怎麼去使用了檢測這個null呢?不停的使用if判斷顯然是不合乎設計的,於是我么的let應運而生

The Kotlin standard library function let can be used for scoping and null-checks.   When called on an object, let executes the given block of code and   returns the result of its last expression.  The object is accessible inside the block by the reference it.

官方文檔中說的很明了let是對標準庫的一個擴展,是作為對null 檢測的一個擴展

fun letFun() {      val empty = "test".let {          customPrint(it)      }      println("is empty: $empty")      fun printNonNull(str: String?) {          println("Printing "$str"")          str?.let {              print("t")              customPrint(it)              println()          }      }      printNonNull(null)      printNonNull("my string")  }

在我們的測試列印中null 和 my string分別作為參數測試時null並沒有走let這個閉包,從而可以看出let只有在非null的情況下才會走對應的閉包

run

和let相似,run是標準庫的另一個擴展。對於基本的用法和let一樣都是內部執行一個閉包並返回自身數據。不同的是run內部走的是一個this的引用,這要說明了內部你可以直接調用對已實例自身的方法

fun runFun() {      fun getNullableLengt(ns: String) {          println("for "$ns":")          ns.run {              println("tis empty? " + this.isEmpty())              println("tlenght =${this.length}")          }      }  }

上栗中我們直接使用this調用Sting對應打方法,當然從run的介紹可以看出this是完全可以省略的,我們只是為了讓大家看的明顯才吧對應的this添加進去而已