作用域函数(Scope Functions)
| 函数 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| let | it | lambda result | 非空对象执行代码块 |
| apply | this | 上下文对象 | 用于对象配置操作 |
| also | it | 上下问对象 | 执行额外操作 |
| run | this | lambda result | 用于对象配置和计算结果 |
| with | this | lambda result | 非扩展函数,配置和计算 |
takeIf 和 takeUnless
takeIf满足条件返回对象,否则返回null;takeUnless和takeIf相反,满足条件返回null,否则返回对象。
能很好地
链式调用,组合使用作用域函数,很实用。
例子:
实现 匹配字符串 并打印 位置功能
str.indexOf(sub).takeIf { it >= 0 }?.let {println("start position: ${it}");
}
文档
- Scope functions