首页 > 解决方案 > kotlin 中的 use{} 和 apply{} 有什么区别?

问题描述

cursor?.apply{
    this.moveToFirst() 
}

cursor?.use{
    it.moveToFirst() 
}

我看到的唯一区别是itand this,这是同一个实例。但是,还有其他区别吗?

标签: kotlin

解决方案


use()只能用Closeable接收器调用。块执行后,Closeable资源关闭,节省样板文件。

您可以查看https://kotlinlang.org/docs/scope-functions.html以获取有关所有范围函数的更多信息。use()本质上与 相同let(),除了具有额外的自动关闭功能。


推荐阅读