February 2018
Intermediate to advanced
350 pages
7h 35m
English
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.Tryfun 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 ...
Read now
Unlock full access