Try is a representation of a computation that may or may not fail. Try<A>
is a sealed class with two possibles sub-classes—Failure<A>
, representing a fail and Success<T>
representing a successful operation.
Let's write our division example with Try
:
import arrow.data.Try fun tryDivide(num: Int, den: Int): Try<Int> = Try { divide(num, den)!! }
The easiest way to create a Try
instance is to use the Try.invoke
operator. If the block inside throws an exception, it will return Failure
; if everything goes well, Success<Int>
, for example, the !!
operator will throw NPE
if divide returns a null:
fun tryDivision(a: Int, b: Int, den: Int): Try<Tuple2<Int, Int>> { val aDiv = tryDivide(a, den) return when (aDiv) { is Success -> { val bDiv = tryDivide(b, den) when (bDiv) { is Success -> { Try { aDiv.value toT bDiv.value } } is Failure -> Failure(bDiv.exception) ...