Skip to content

Commit d7dbf35

Browse files
Kirill Zhukovmichaelbull
Kirill Zhukov
authored andcommitted
Improve type constraint on toErrorIfNull
Closes #84 and closes #86
1 parent ebe8f33 commit d7dbf35

File tree

3 files changed

+24
-11
lines changed

3 files changed

+24
-11
lines changed

build.gradle.kts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,11 @@ subprojects {
223223
name.set("Matthias Geisler")
224224
url.set("https://github.com/bitPogo")
225225
}
226+
227+
contributor {
228+
name.set("Kirill Zhukov")
229+
url.set("https://github.com/kirillzh")
230+
}
226231
}
227232

228233
scm {

kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Map.kt

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -195,15 +195,19 @@ public inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, trans
195195
*
196196
* @see [toErrorIf]
197197
*/
198-
public inline fun <V, E> Result<V, E>.toErrorIfNull(error: () -> E): Result<V, E> {
198+
public inline fun <V, E> Result<V?, E>.toErrorIfNull(error: () -> E): Result<V, E> {
199199
contract {
200200
callsInPlace(error, InvocationKind.AT_MOST_ONCE)
201201
}
202202

203-
return toErrorIf(
204-
{ it == null },
205-
{ error() }
206-
)
203+
return when (this) {
204+
is Ok -> if(value == null) {
205+
Err(error())
206+
} else {
207+
Ok(value)
208+
}
209+
is Err -> this
210+
}
207211
}
208212

209213
/**
@@ -239,8 +243,12 @@ public inline fun <V, E> Result<V, E>.toErrorUnlessNull(error: () -> E): Result<
239243
callsInPlace(error, InvocationKind.AT_MOST_ONCE)
240244
}
241245

242-
return toErrorUnless(
243-
{ it == null },
244-
{ error() }
245-
)
246+
return when (this) {
247+
is Ok -> if (value == null) {
248+
this
249+
} else {
250+
Err(error())
251+
}
252+
is Err -> Err(error())
253+
}
246254
}

kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/MapTest.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ class MapTest {
192192

193193
@Test
194194
fun returnsTransformedErrorIfNull() {
195-
val result = Ok(null).toErrorIfNull { "a" }
195+
val result: Result<Nothing, String> = Ok(null).toErrorIfNull { "a" }
196196

197197
result as Err
198198

@@ -245,7 +245,7 @@ class MapTest {
245245
result as Err
246246

247247
assertEquals(
248-
expected = "a",
248+
expected = "b",
249249
actual = result.error
250250
)
251251
}

0 commit comments

Comments
 (0)