Kotlin 標(biāo)準(zhǔn)庫擴(kuò)展函數(shù)

Kotlin 標(biāo)準(zhǔn)庫提供了一些擴(kuò)展 Java 庫的函數(shù)。

  • apply

apply 是 Any 的擴(kuò)展函數(shù), 因而所有類型都能調(diào)用。
apply 接受一個(gè)lambda表達(dá)式作為參數(shù),并在apply調(diào)用時(shí)立即執(zhí)行,apply返回原來的對(duì)象。
apply 主要作用是將多個(gè)初始化代碼鏈?zhǔn)讲僮鳎岣叽a可讀性。
如:

val task = Runnable { println("Running") }
Thread(task).apply { setDaemon(true) }.start()

上面代碼相對(duì)于

val task = Runnable { println("Running") }
val thread = Thread(task)
thread.setDaemon(true)
thread.start()
  • let

let 和 apply 類似, 唯一的不同是返回值,let返回的不是原來的對(duì)象,而是閉包里面的值。

val outputPath = Paths.get("/user/home").let {
    val path = it.resolve("output")
    path.toFile().createNewFile()
    path
}

outputPath 結(jié)果是閉包里面的 path。

  • with

with 是一個(gè)頂級(jí)函數(shù), 當(dāng)你想調(diào)用對(duì)象的多個(gè)方法但是不想重復(fù)對(duì)象引用,比如代碼:

val g2: Graphics2D = ...
g2.stroke = BasicStroke(10F)
g2.setRenderingHint(...)
g2.background = Color.BLACK

可以用 with 這樣寫:

with(g2) {
    stroke = BasicStroke(10F)
    setRenderingHint(...)
    background = Color.BLACK
}
  • run

run 是 with和let 的組合,例如

val outputPath = Paths.get("/user/home").run {
    val path = resolve("output")
    path.toFile().createNewFile()
    path
}
  • lazy

lazy延遲運(yùn)算,當(dāng)?shù)谝淮卧L問時(shí),調(diào)用相應(yīng)的初始化函數(shù),例如:

fun readFromDb(): String = ...
val lazyString = lazy { readFromDb() }

val string = lazyString.value

當(dāng)?shù)谝淮问褂?lazyString時(shí), lazy 閉包會(huì)調(diào)用。一般用在單例模式。

  • use

use 用在 Java 上的 try-with-resources 表達(dá)式上, 例如:

val input = Files.newInputStream(Paths.get("input.txt"))
val byte = input.use({ input.read() })

use 無論如何都會(huì)將 input close, 避免了寫復(fù)雜的 try-catch-finally 代碼。

  • repeat

顧名思義,repeat 接受函數(shù)和整數(shù)作為參數(shù),函數(shù)會(huì)被調(diào)用 k 次,這個(gè)函數(shù)避免寫循環(huán)。
repeat(10, { println("Hello") })

  • require/assert/check

require/assert/check 用來檢測(cè)條件是否為true, 否則拋出異常。
require 用在參數(shù)檢查;
assert/check 用在內(nèi)部狀態(tài)檢查, assert 拋出 AssertionException, check 拋出 IllegalStateException。

示例

fun neverEmpty(str: String) {
    require(str.length > 0, { "String should not be empty" })
    println(str)
}

參考
《Programming Kotlin》Stephen Samuel ,Stefan Bocutiu
《Kotlin in Action》Dmitry Jemerov,Svetlana Isakova

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容