Skip to content

Commit

Permalink
Merge pull request #736 from stoyle/master
Browse files Browse the repository at this point in the history
Allow exception to propagate from fold Success function
  • Loading branch information
pakoito committed Mar 21, 2018
2 parents 863232b + a49eae6 commit 71ec421
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
8 changes: 1 addition & 7 deletions modules/core/arrow-core/src/main/kotlin/arrow/core/Try.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,17 +81,11 @@ sealed class Try<out A> : TryOf<A> {

/**
* Applies `fa` if this is a `Failure` or `fb` if this is a `Success`.
* If `fb` is initially applied and throws an exception,
* then `fa` is applied with this exception.
*/
inline fun <B> fold(fa: (Throwable) -> B, fb: (A) -> B): B =
when (this) {
is Failure -> fa(exception)
is Success -> try {
fb(value)
} catch (e: Throwable) {
fa(e)
}
is Success -> fb(value)
}

abstract fun isFailure(): Boolean
Expand Down
12 changes: 10 additions & 2 deletions modules/core/arrow-data/src/test/kotlin/arrow/data/TryTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import arrow.test.laws.ShowLaws
import arrow.test.laws.TraverseLaws
import arrow.typeclasses.*
import io.kotlintest.KTestJUnitRunner
import io.kotlintest.matchers.beTheSameInstanceAs
import io.kotlintest.matchers.fail
import io.kotlintest.matchers.should
import io.kotlintest.matchers.shouldBe
import io.kotlintest.matchers.shouldEqual
import io.kotlintest.matchers.shouldNotBe
Expand Down Expand Up @@ -76,8 +78,14 @@ class TryTest : UnitSpec() {
Success(1).fold({ 2 }, { 3 }) shouldBe 3
}

"fold should call left function on Success with exception" {
Success(1).fold({ 2 }, { throw Exception() }) shouldBe 2
"fold should propagate exception from Success with exception" {
Exception().let { ex ->
try {
Success(1).fold({ 2 }, { throw ex })
} catch (e: Exception) {
ex should beTheSameInstanceAs(e)
}
}
}

"getOrDefault returns default if Failure" {
Expand Down

0 comments on commit 71ec421

Please sign in to comment.