• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

卢晓春的博客

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

安卓笔记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()

posted on 2025-01-04 22:09  卢晓春  阅读(20)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3