Auto Closeable
Начиная с Kotlin: 2.0
expect inline fun AutoCloseable(crossinline closeAction: () -> Unit): AutoCloseable
Возвращает экземпляр AutoCloseable, который при вызове своей функции close() выполняет указанное действие closeAction.
Эта функция позволяет задавать пользовательские действия по очистке ресурсов.
Обратите внимание: каждый вызов функции close() для возвращённого экземпляра AutoCloseable выполняет действие closeAction. Поэтому настоятельно рекомендуется, чтобы реализация closeAction была идемпотентной или чтобы повторные вызовы были предотвращены.
Пример:
val autoCloseable = AutoCloseable {
// Cleanup action, e.g., closing a file or releasing a network connection
Logger.log("Releasing the network connection.")
networkConnection.release()
}
// Now you can pass the autoCloseable to a function or use it directly.
autoCloseable.use {
// Use the connection, which will be automatically released when this scope finishes.
val content = networkConnection.readContent()
Logger.log("Network connection content: $content")
}
См. также
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-auto-closeable.html