[Kotlin标准函数] run、with、apply、also、let、use等

文章目录

  • [1. let](#1. let)
  • [2. with](#2. with)
    • [2.1 参数解析](#2.1 参数解析)
    • [2.2 用法示例](#2.2 用法示例)
  • 3、use函数

1. let

2. with

2.1 参数解析

第一个参数可以是一个任意类型的对象,

第二个参数是一个Lambda表达式

with函数会在Lambda表达式中提供第一个参数对象的上下文,

并使用Lambda表达式中的最后一行代码作为返回值返回

2.2 用法示例

kotlin 复制代码
val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape")
val result = with(StringBuilder()) {
append("Start eating fruits.\n")
for (fruit in list) {
append(fruit).append("\n")
}
append("Ate all fruits.")
toString()
}
println(result)
// 输出
Strat eating fruits.
A
B
..
Ate all fruits

3、use函数

  • 实现了Closeable接口的对象可调用use函数
  • use函数会自动关闭调用者(无论中间是否出现异常)
  • 代码对比
    Java
java 复制代码
public void saveBitmapToFile(Bitmap bitmap, String filePath) {
    try {
        FileOutputStream out = new FileOutputStream(filePath);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Kotlin

java 复制代码
fun saveBitmapToFile(bitmap: Bitmap, filePath: String) {
    try {
        FileOutputStream(filePath).use { out ->
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
相关推荐
curdcv_po11 分钟前
甲方嫌弃,项目首页加载太慢
前端
.似水12 分钟前
Python requests
开发语言·python
刘同学有点忙13 分钟前
技术升级中的"幽灵Bug"排查:从message失效看架构迁移的隐性成本
前端
不会飞的鲨鱼14 分钟前
FastMoss 国际电商Tiktok数据分析 JS 逆向 | MD5加密
javascript·python·数据挖掘·数据分析
怪大叔952714 分钟前
vue组件之远程组件
前端·javascript·vue.js
邢同学爱折腾15 分钟前
长安的荔枝小说阅读器——程序员的浪漫与效率
前端·javascript
墨夏17 分钟前
Tauri + NextJS 扫码登录
android·前端·ios
天生我材必有用_吴用19 分钟前
Three.js开发必备:灯光详解附带案例
前端
tanyyinyu32 分钟前
Python列表:高效灵活的数据存储与操作指南
开发语言·windows·python
heeheeai35 分钟前
kotlin kmp 副作用函数 effect
kotlin·effect·kmp·副作用函数