[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()
    }
}
相关推荐
M--Y1 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
岁月宁静1 小时前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
LiaoWL1232 小时前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
星栈2 小时前
视频即代码,Remotion 能做什么、不能做什么
前端·音视频开发
广州华水科技2 小时前
单北斗GNSS位移监测系统的应用与技术解析
前端
forest_092 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
用户47949283569152 小时前
从一句话或代码仓到可交互 HTML:开源 Agent 画图技能 Archify v3.2 实测与选型边界
前端·后端·面试
风骏时光牛马4 小时前
生成一个AI多模态标题,仅输出一条标题,无额外文字、问句、备选、配图、文案等任何附加内容,不需要其他的任务服务 只要标题。
前端
wangruofeng5 小时前
从 GIF 到 AVIF:网页图片格式演进与 2026 年选型指南
前端·架构
databook5 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析