From fe6ac99a29ec207c9c5f4421f3fed62fd5bc9d45 Mon Sep 17 00:00:00 2001 From: Matthew Nelson Date: Tue, 5 Mar 2024 09:13:12 -0500 Subject: [PATCH] Fix `Closeable.use` `NullPointerException` (#1453) * Fix Cloneable.use NullPointerException * Add assertNull --- okio/src/commonMain/kotlin/okio/Okio.kt | 9 +++++---- okio/src/nonWasmTest/kotlin/okio/UseTest.kt | 10 ++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/okio/src/commonMain/kotlin/okio/Okio.kt b/okio/src/commonMain/kotlin/okio/Okio.kt index 861d51121f..a0a420bbc3 100644 --- a/okio/src/commonMain/kotlin/okio/Okio.kt +++ b/okio/src/commonMain/kotlin/okio/Okio.kt @@ -49,13 +49,13 @@ private class BlackholeSink : Sink { /** Execute [block] then close this. This will be closed even if [block] throws. */ inline fun T.use(block: (T) -> R): R { - var result: R? = null var thrown: Throwable? = null - try { - result = block(this) + val result = try { + block(this) } catch (t: Throwable) { thrown = t + null } finally { try { this?.close() @@ -69,5 +69,6 @@ inline fun T.use(block: (T) -> R): R { } if (thrown != null) throw thrown - return result!! + @Suppress("UNCHECKED_CAST") + return result as R } diff --git a/okio/src/nonWasmTest/kotlin/okio/UseTest.kt b/okio/src/nonWasmTest/kotlin/okio/UseTest.kt index a36cf06867..3cf713b390 100644 --- a/okio/src/nonWasmTest/kotlin/okio/UseTest.kt +++ b/okio/src/nonWasmTest/kotlin/okio/UseTest.kt @@ -1,6 +1,7 @@ package okio import kotlin.test.Test +import kotlin.test.assertNull import okio.Path.Companion.toPath import okio.fakefilesystem.FakeFileSystem @@ -25,4 +26,13 @@ class UseTest { fakeFileSystem.checkNoOpenFiles() } + + @Test + fun acceptsNullReturn() { + val result = object : Closeable { + override fun close() {} + }.use { null } + + assertNull(result) + } }