Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow exception to propagate from fold Success function #736

Merged
merged 1 commit into from
Mar 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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