安卓笔记3——kotlin不写必忘的标准方法
标准函数
with
接受2个参数,一个提供默认调用的对象,另一个是lambda
当反复调用同一个对象时,方便省略
最后一行作为函数返回值
val result = with(StringBuilder()) {
append("xxx")
append("xxx")
append("xxx")
}
run
与with类似,但是只接受一个lambda参数,内部的默认调用对象由调用者提供
val result = StringBuilder().run {
append("xxx")
append("xxx")
append("xxx")
}
apply
与run类似,但是返回调用者本身(有函数式编程的感觉)
let
主要用于配合?.进行判空检查
student?.let{
student.study()
student.play()
}
// 避免
student?.study()
student?.play()
浙公网安备 33010602011771号