Вы можете увидеть исходный код для use
в stdlib
, перейдя с помощью «Go к реализации» ( Cmd + B на Ma c):
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
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
}
}
}
}
Поскольку вызов close
находится внутри блока finally, он будет выполнен даже при досрочном возврате.