Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scalaz._
- /**
- * Tries[T] is a type alias of Throwable \/ T.
- * It can be used in the same manner as scala.util.Try but it is an instance of monad unlike Try.
- *
- * Created by phenan on 2017/10/18.
- */
- package object tries {
- type Tries[+T] = Throwable \/ T
- object Tries {
- def apply [T] (v: => T): Tries[T] = try \/-(v) catch { case e: Throwable => -\/(e) }
- }
- object Succeeds {
- def apply [T] (v: => T): Tries[T] = \/-(v)
- }
- object Fails {
- def apply (e: => Throwable): Tries[Nothing] = -\/(e)
- }
- implicit class TriesUtil [T] (t: Tries[T]) {
- def filters (f: T => Boolean): Tries[T] = t match {
- case \/-(v) if f(v) => \/-(v)
- case \/-(v) => -\/(new NoSuchElementException("Predicate does not hold for " + v))
- case -\/(e) => -\/(e)
- }
- def catches (f: PartialFunction[Throwable, T]): T = t match {
- case \/-(v) => v
- case -\/(e) if f.isDefinedAt(e) => f(e)
- case -\/(e) => throw e
- }
- }
- }
Add Comment
Please, Sign In to add comment