kotlin use函数
简述
use函数是kotlin的语法糖,用于在使用资源(如文件、流等)后自动关闭它们。使用 use
函数可以确保资源在不再需要时被正确释放,从而避免资源泄漏和其他问题。
和我们写try with resource是一样的,使用use会自动close资源
use函数只能用于实现了 Closeable
接口的类
例子
例如我们想写一个读取文件的方法,使用java写要:
public class Example { public static void main(String[] args) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("file.txt")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
可以看到我们要捕捉很多异常,同时要手动关闭资源
如果用kotlin来写,则简单许多
fun main() { val file = File("file.txt") file.bufferedReader().use { reader -> reader.forEachLine { line -> println(line) } } }
use函数会自动帮你捕捉异常,然后自动释放资源
源码分析
可以看到use函数内部帮你捕捉了异常,同时自动关闭调用者对象所属的资源
@InlineOnly @RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.") public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } var exception: Throwable? = null try { return block(this) } catch (e: Throwable) { exception = e throw e } finally { when { apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception) this == null -> {} exception == null -> close() else -> try { close() } catch (closeException: Throwable) { // cause.addSuppressed(closeException) // ignored here } } } }
一点一点积累,一点一点蜕变!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!