com.thoughtworks.zerocost.tryt
A monad transformer for exception handling.
As a monad transformer, TryT should be used with another monadic data type, like scala.Function0.
TryT
import cats.instances.function._ import scala.util._ import com.thoughtworks.zerocost.tryt._ type TryName[+A] = TryT[Function0, A]
Given a validate function,
validate
def validate(s: String): Int = s.toInt
when creating a TryT-transformed scala.Function0 from the validate,
import cats.syntax.all._ val invalidTry: TryName[Int] = TryT(() => Try(validate("invalid input")))
then the exceptions thrown in validate call should be converted to a scala.util.Failure;
val TryT(failure) = invalidTry failure() should be(an[Failure[_]])
and when there is no exception thrown in validate call,
val validTry: TryName[Int] = validate("42").pure[TryName]
then the result of validate call should be converted to a scala.util.Success;
val TryT(success) = validTry success() should be(Success(42))
and when the TryT-transformed scala.Function0 is built from a for-comprehension,
for
val invalidForComprehension: TryName[Int] = validate("42").pure[TryName].flatMap { i => validate("invalid input").pure[TryName].map { j => i + j } }
then the exceptions thrown in the for-comprehension should be converted to a scala.util.Failure;
val TryT(failure2) = invalidTry failure2() should be(an[Failure[_]])
This TryT type is an opacity alias to F[Try[A]]. All type classes and helper functions for this TryT type are defined in the companion object TryT
F[Try[A]]
This TryT transfomer is similar to cats.data.EitherT, except TryT handles exceptions thrown in callback functions passed to map, flatMap or pure.
A monad transformer for exception handling.
As a monad transformer,
TryT
should be used with another monadic data type, like scala.Function0.Given a
validate
function,when creating a
TryT
-transformed scala.Function0 from thevalidate
,then the exceptions thrown in
validate
call should be converted to a scala.util.Failure;val TryT(failure) = invalidTry failure() should be(an[Failure[_]])
and when there is no exception thrown in
validate
call,then the result of
validate
call should be converted to a scala.util.Success;and when the
TryT
-transformed scala.Function0 is built from afor
-comprehension,then the exceptions thrown in the
for
-comprehension should be converted to a scala.util.Failure;val TryT(failure2) = invalidTry failure2() should be(an[Failure[_]])
This
TryT
type is an opacity alias toF[Try[A]]
. All type classes and helper functions for thisTryT
type are defined in the companion object TryTThis
TryT
transfomer is similar to cats.data.EitherT, exceptTryT
handles exceptions thrown in callback functions passed to map, flatMap or pure.