Add flatMap for Result type (#51)

This commit is contained in:
Andrew Haisting 2023-09-18 14:34:25 -05:00 committed by Álison Fernandes
parent 70ec944469
commit 36942ab296
2 changed files with 62 additions and 0 deletions

View file

@ -0,0 +1,10 @@
package com.x8bit.bitwarden.data.platform.util
/**
* Flat maps a successful [Result] with the given [transform] to another [Result], and leaves
* failures untouched.
*/
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> =
this.exceptionOrNull()
?.let { Result.failure(it) }
?: transform(this.getOrThrow())

View file

@ -0,0 +1,52 @@
package com.x8bit.bitwarden.data.platform.util
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class ResultTest {
@Test
fun `flatMap where receiver is success and argument is success should be argument success`() {
val intResult = Result.success(1)
val stringResult = intResult.flatMap {
Result.success(it.toString())
}
assertTrue(stringResult.isSuccess)
assertEquals("1", stringResult.getOrNull())
}
@Test
fun `flatMap where receiver is success and argument is failure should be argument failure`() {
val expectedException = IllegalStateException("Exception in transform")
val intResult = Result.success(1)
val stringResult = intResult.flatMap {
Result.failure<String>(expectedException)
}
assertTrue(stringResult.isFailure)
assertEquals(expectedException, stringResult.exceptionOrNull())
}
@Test
@Suppress("TooGenericExceptionThrown")
fun `flatMap where receiver is failure and argument is failure should be receiver failure`() {
val expectedException = RuntimeException("Exception on int result.")
val intResult = Result.failure<Int>(expectedException)
val stringResult = intResult.flatMap<Int, String> {
throw RuntimeException("transform function should not be called for failed Results")
}
assertTrue(stringResult.isFailure)
assertEquals(expectedException, stringResult.exceptionOrNull())
}
@Test
fun `flatMap where receiver is failure and argument is success should be receiver failure`() {
val expectedException = RuntimeException("Exception on int result.")
val intResult = Result.failure<Int>(expectedException)
val stringResult = intResult.flatMap {
Result.success("1")
}
assertTrue(stringResult.isFailure)
assertEquals(expectedException, stringResult.exceptionOrNull())
}
}