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

猜你喜欢

转载自blog.csdn.net/xiaoluoli88/article/details/78122119