Skip to content

Commit

Permalink
[Feature] Add get failure or null (#88)
Browse files Browse the repository at this point in the history
  • Loading branch information
kittinunf authored Jul 17, 2021
1 parent 7086a0e commit 121a826
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 37 deletions.
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ local.properties
.classpath
.project

# Bintray
bintray_push.sh

# Android Studio
.idea/
.gradle
Expand Down
17 changes: 0 additions & 17 deletions .travis.yml

This file was deleted.

16 changes: 0 additions & 16 deletions deploy_bintray.sh

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ fun <V, E : Throwable> Result<V, E>.getOrNull(): V? = when (this) {
is Result.Failure -> null
}

fun <V, E : Throwable> Result<V, E>.getFailureOrNull(): E? = when (this) {
is Result.Success -> null
is Result.Failure -> error
}

inline infix fun <V, E : Exception> Result<V, E>.getOrElse(fallback: (E) -> V): V = when (this) {
is Result.Success -> value
is Result.Failure -> fallback(error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,24 @@ class ResultTest {
assertEquals(Kind.Failure, v.kind)
}

@Test
fun `should get return value and get failure return null for result with success`() {
val s = Result.of<Int, IllegalStateException> { 42 }

assertNull(s.getFailureOrNull())
assertNotNull(s.getOrNull())
assertEquals(42, s.getOrNull())
}

@Test
fun `should get return null and get failure return error for result with failure`() {
val f = Result.of<String, IllegalStateException> { throw IllegalStateException("foo") }

assertNull(f.getOrNull())
assertNotNull(f.getFailureOrNull())
assertIs<IllegalStateException>(f.getFailureOrNull())
}

@Test
fun `should create value with success`() {
val s = Result.success(42)
Expand All @@ -46,7 +64,6 @@ class ResultTest {
val e = Result.failure(RuntimeException())
val err = e.component2()

assertNull(e.getOrNull())
assertNull(e.component1())
assertNotNull(err)
}
Expand Down

0 comments on commit 121a826

Please sign in to comment.