Skip to content

Instantly share code, notes, and snippets.

@justinhj
Last active February 25, 2020 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinhj/d01704336b9640044d37ad8cedb644ea to your computer and use it in GitHub Desktop.
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)
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