Kotlin 标准库扩展函数

Kotlin 标准库提供了一些扩展 Java 库的函数。

  • apply

apply 是 Any 的扩展函数, 因而所有类型都能调用。
apply 接受一个lambda表达式作为参数,并在apply调用时立即执行,apply返回原来的对象。
apply 主要作用是将多个初始化代码链式操作,提高代码可读性。
如:

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

上面代码相对于

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

let 和 apply 类似, 唯一的不同是返回值,let返回的不是原来的对象,而是闭包里面的值。

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

outputPath 结果是闭包里面的 path。

  • with

with 是一个顶级函数, 当你想调用对象的多个方法但是不想重复对象引用,比如代码:

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延迟运算,当第一次访问时,调用相应的初始化函数,例如:

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

val string = lazyString.value

当第一次使用 lazyString时, lazy 闭包会调用。一般用在单例模式。

  • use

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

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

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)
}

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值