Last active
February 25, 2020 02:36
-
-
Save justinhj/d01704336b9640044d37ad8cedb644ea to your computer and use it in GitHub Desktop.
I called this Throwable but it's actually just an implementation of Try (and Functor/Monad instance of it)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object MyThrowable { | |
// This is just here to keep Wartremover happy | |
@SuppressWarnings(Array("org.wartremover.warts.Equals")) | |
implicit final class AnyOps[A](self: A) { | |
def ===(other: A): Boolean = self == other | |
} | |
// Define Try and make it a monad/functor | |
sealed trait Try[+T] | |
final case class Success[+T](value: T) extends Try[T] | |
final case class Failure[+T](throwable: Throwable) extends Try[Nothing] | |
final implicit class TryOps[A](val `try`: Try[A]) extends AnyVal { | |
def flatMap[B](f: A => Try[B]): Try[B] = { | |
`try` match { | |
case Success(a) => | |
f(a) | |
case Failure(fail) => | |
Failure[B](fail) | |
} | |
} | |
def map[B](f: A => B): Try[B] = { | |
`try` match { | |
case Success(a) => | |
unit(f(a)) | |
case Failure(fail) => | |
Failure[B](fail) | |
} | |
} | |
def unit[C](c: C) = Success(c) | |
} | |
def tryOrOOM(m: Int): Try[Int] = { | |
if(m === 1) { | |
val s = Success(1) | |
s | |
} | |
else { | |
val f = Failure[Int](new IllegalArgumentException("I only like ones")) | |
f | |
} | |
} | |
val ok = for ( | |
a <- tryOrOOM(1); | |
b <- tryOrOOM(a) | |
) yield b | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment