[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()
    }
}
相关推荐
モンキー・D・小菜鸡儿8 分钟前
Android14 新特性与适配指南
android·kotlin·安卓新特性
学历真的很重要18 分钟前
PyTorch 机器学习工作流程基础 - 完整教程
人工智能·pytorch·后端·python·深度学习·机器学习·面试
毕设源码-朱学姐26 分钟前
【开题答辩全过程】以 基于vue.js的校园二手平台为例,包含答辩的问题和答案
前端·javascript·vue.js
m0_4711996340 分钟前
【JavaScript】Set 和 Map 核心区别与实战用法(ES6 集合全解析)
前端·javascript·es6
小白学大数据1 小时前
基于文本检测的 Python 爬虫弹窗图片定位与拖动实现
开发语言·爬虫·python
hoiii1871 小时前
MATLAB中主成分分析(PCA)与相关性分析的实现
前端·人工智能·matlab
大波V51 小时前
用 nvm 彻底重装 Node 12.22.12(确保干净)
前端
努力的BigJiang1 小时前
ORB-SLAM2在ubuntu20.04中的复现记录(跑数据集+ROS)(ROS接口失败版)
python
和和和2 小时前
React Scheduler为何采用MessageChannel调度?
前端·javascript
Ric9702 小时前
Mac上Git不识别文件名大小写修改?一招搞定!
前端