recover

inline fun <E, EE, A> Either<E, A>.recover(recover: RecoverEffect<EE>.(E) -> A): Either<EE, A>

Recover from any Either.Left if encountered.

The recover DSL allows you to recover from any Either.Left value by:

  • Computing a fallback value A, and resolve the left type E to Nothing.

  • Shifting a new error of type EE into the Either.Left channel.

When providing a fallback value A, the Either.Left type is discarded because the error was handled correctly.

import arrow.core.Either
import arrow.core.recover
import io.kotest.matchers.shouldBe

fun test() {
val error: Either<String, Int> = Either.Left("error")
val fallback: Either<Nothing, Int> = error.recover { it.length }
fallback shouldBe Either.Right(5)
}

When shifting a new error EE into the Either.Left channel, the Either.Left is transformed from E to EE since we shifted a new error.

import arrow.core.Either
import arrow.core.recover
import io.kotest.matchers.shouldBe

fun test() {
val error: Either<String, Int> = Either.Left("error")
val listOfErrors: Either<List<Char>, Int> = error.recover { shift(it.toList()) }
listOfErrors shouldBe Either.Left(listOf('e', 'r', 'r', 'o', 'r'))
}