diff --git a/okio/src/commonMain/kotlin/okio/Okio.kt b/okio/src/commonMain/kotlin/okio/Okio.kt index 116678aa1f..96b1efe24a 100644 --- a/okio/src/commonMain/kotlin/okio/Okio.kt +++ b/okio/src/commonMain/kotlin/okio/Okio.kt @@ -56,13 +56,13 @@ inline fun T.use(block: (T) -> R): R { result = block(this) } catch (t: Throwable) { thrown = t - } - - try { - this?.close() - } catch (t: Throwable) { - if (thrown == null) thrown = t - else thrown.addSuppressed(t) + } finally { + try { + this?.close() + } catch (t: Throwable) { + if (thrown == null) thrown = t + else thrown.addSuppressed(t) + } } if (thrown != null) throw thrown diff --git a/okio/src/commonTest/kotlin/okio/UseTest.kt b/okio/src/commonTest/kotlin/okio/UseTest.kt new file mode 100644 index 0000000000..06b7cb8480 --- /dev/null +++ b/okio/src/commonTest/kotlin/okio/UseTest.kt @@ -0,0 +1,28 @@ +package okio + +import okio.Path.Companion.toPath +import okio.fakefilesystem.FakeFileSystem +import kotlin.test.Test + +class UseTest { + val fakeFileSystem = FakeFileSystem(clock = FakeClock()).also { it.emulateUnix() } + + val base = "/cache".toPath().also { + fakeFileSystem.createDirectories(it) + } + + @Test + fun closesWithUseBlock() { + fun testMethodWithUse() { + val sink = fakeFileSystem.sink(base / "all-files-includes-file") + + sink.use { + return@testMethodWithUse + } + } + + testMethodWithUse() + + fakeFileSystem.checkNoOpenFiles() + } +}