Skip to content

Commit

Permalink
Favor Either and IO instead of Try (arrow-kt#1478)
Browse files Browse the repository at this point in the history
* Add catch constructor to Either

* Add other catch constructor to Either

* Add deprecation notices in favor of Either

* Fix ReplaceWith

* Make Either constructors suspend

* Improve Try deprecation notice
  • Loading branch information
pakoito authored and nomisRev committed Jul 22, 2019
1 parent 31756f9 commit b6f0145
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions modules/core/arrow-core-data/src/main/kotlin/arrow/core/Either.kt
Expand Up @@ -189,6 +189,16 @@ sealed class Either<out A, out B> : EitherOf<A, B> {
}

fun <L, R> cond(test: Boolean, ifTrue: () -> R, ifFalse: () -> L): Either<L, R> = if (test) right(ifTrue()) else left(ifFalse())

suspend fun <R> catch(f: suspend () -> R): Either<Throwable, R> =
catch(::identity, f)

suspend fun <L, R> catch(fe: (Throwable) -> L, f: suspend () -> R): Either<L, R> =
try {
f().right()
} catch (t: Throwable) {
fe(t.nonFatalOrThrow()).left()
}
}
}

Expand Down
16 changes: 16 additions & 0 deletions modules/core/arrow-core-data/src/main/kotlin/arrow/core/Try.kt
Expand Up @@ -16,8 +16,16 @@ sealed class Try<out A> : TryOf<A> {

companion object {

@Deprecated(
"Try promotes eager execution of effects, so it's better if you work with suspend Either constructors or a an effect handler like IO",
ReplaceWith("Either.just(a)")
)
fun <A> just(a: A): Try<A> = Success(a)

@Deprecated(
"Try promotes eager execution of effects, so it's better if you work with suspend Either constructors or a an effect handler like IO",
ReplaceWith("Either.tailRecM(a, f)")
)
tailrec fun <A, B> tailRecM(a: A, f: (A) -> TryOf<Either<A, B>>): Try<B> {
val ev: Try<Either<A, B>> = f(a).fix()
return when (ev) {
Expand All @@ -32,6 +40,10 @@ sealed class Try<out A> : TryOf<A> {
}
}

@Deprecated(
"Try promotes eager execution of effects, so it's better if you work with suspend Either constructors or a an effect handler like IO",
ReplaceWith("Either.catch(f)")
)
inline operator fun <A> invoke(f: () -> A): Try<A> =
try {
Success(f())
Expand All @@ -43,6 +55,10 @@ sealed class Try<out A> : TryOf<A> {
}
}

@Deprecated(
"Try promotes eager execution of effects, so it's better if you work with suspend Either constructors or a an effect handler like IO",
ReplaceWith("Either.raiseError(e)")
)
fun raiseError(e: Throwable): Try<Nothing> = Failure(e)
}

Expand Down

0 comments on commit b6f0145

Please sign in to comment.