Kotlin 标准库扩展函数
来源:互联网 发布:无线路由器破解软件 编辑:程序博客网 时间:2024/06/06 00:59
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
- Kotlin 标准库扩展函数
- Kotlin 标准库扩展函数
- android kotlin扩展函数
- Kotlin 扩展函数/属性
- kotlin随笔—扩展函数
- kotlin学习day11:扩展函数
- kotlin的扩展函数和扩展属性
- kotlin源码分析-标准内置函数
- Kotlin-12.扩展函数和属性(extensions)
- Kotlin 扩展函数详解与应用
- Kotlin 扩展函数 与 JS 的 prototype
- 解析Kotlin函数和属性扩展
- Kotlin委托&扩展&高阶函数
- Kotlin-扩展
- kotlin-扩展
- Kotlin 扩展
- Kotlin 扩展
- Kotlin学习笔记——标准库kotlin
- Android Studio 百度地图 230错误 Scode码校验失败
- ajax整理
- Thinkphp文件锁处理高并发
- 51nod 1799 二分答案 (打表)
- Linux基础-9(crond)
- Kotlin 标准库扩展函数
- 决策树算法总结
- 元字符与转义(正则基本知识abc)
- 消息邮箱和消息队列
- 软件工程工作必备
- [二]Spring Boot 热部署
- windows安装XGBoost
- sql语句的优化
- andoid HorizontalScrollView 水平滚动问题