1. 程式人生 > >Kotlin 標準庫擴充套件函式

Kotlin 標準庫擴充套件函式

Kotlin 標準庫提供了一些擴充套件 Java 庫的函式。

  • apply

apply 是 Any 的擴充套件函式, 因而所有型別都能呼叫。 
apply 接受一個lambda表示式作為引數,並在apply呼叫時立即執行,apply返回原來的物件。 
apply 主要作用是將多個初始化程式碼鏈式操作,提高程式碼可讀性。 
如:

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

上面程式碼相對於

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

let 和 apply 類似, 唯一的不同是返回值,let返回的不是原來的物件,而是閉包裡面的值。

val outputPath = Paths.get("/user/home").let {
    val path = it.resolve("output")
    path.toFile().createNewFile()
    path
}
  • 1
  • 2
  • 3
  • 4
  • 5

outputPath 結果是閉包裡面的 path。

  • with

with 是一個頂級函式, 當你想呼叫物件的多個方法但是不想重複物件引用,比如程式碼:

val g2: Graphics2D = ...
g2.stroke = BasicStroke(10F)
g2.setRenderingHint(...)
g2.background = Color.BLACK
  • 1
  • 2
  • 3
  • 4

可以用 with 這樣寫:

with(g2) {
    stroke = BasicStroke(10F)
    setRenderingHint(...
) background = Color.BLACK }
  • 1
  • 2
  • 3
  • 4
  • 5
  • run

run 是 with和let 的組合,例如

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

lazy延遲運算,當第一次訪問時,呼叫相應的初始化函式,例如:

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

val string = lazyString.value
  • 1
  • 2
  • 3
  • 4

當第一次使用 lazyString時, lazy 閉包會呼叫。一般用在單例模式。

  • use

use 用在 Java 上的 try-with-resources 表示式上, 例如:

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

use 無論如何都會將 input close, 避免了寫複雜的 try-catch-finally 程式碼。

  • repeat

顧名思義,repeat 接受函式和整數作為引數,函式會被呼叫 k 次,這個函式避免寫迴圈。 
repeat(10, { println("Hello") })

  • require/assert/check

require/assert/check 用來檢測條件是否為true, 否則丟擲異常。 
require 用在引數檢查; 
assert/check 用在內部狀態檢查, assert 丟擲 AssertionException, check 丟擲 IllegalStateException。

示例

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

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