Skip to content

Instantly share code, notes, and snippets.

@trane
Last active January 28, 2017 01:02
Show Gist options
  • Save trane/0fe3af3bc613137154a186e813d99531 to your computer and use it in GitHub Desktop.
Save trane/0fe3af3bc613137154a186e813d99531 to your computer and use it in GitHub Desktop.
trait OrElseAble[F[_]] {
def getOrElse[A, B >: A](fa: F[A])(orElse: => B): B
}
object OrElseAble {
implicit val OptionElsable: OrElseAble[Option] = new OrElseAble[Option] {
override def getOrElse[A, B >: A](fa: Option[A])(orElse: => B) = fa.getOrElse(b)
}
implicit val TryElsable: OrElseAble[Try] = new OrElseAble[Try] {
override def getOrElse[A, B >: A](fa: Try[A])(orElse: => B) = fa.getOrElse(b)
}
}
object FutureHelpers {
def toFuture[A, F[_] : OrElseAble](fa: F[A])(onFailure: => Throwable): Future[A] =
Future.successful(
implicitly[OrElseAble[F]]
).map(_.getOrElse(fa)(throw onFailure))
def toFuture[A, B >: A, F[_] : OrElseAble](fa: F[A])(onFailure: => B): Future[B] =
Future.successful(
implicitly[OrElseAble[F]].getOrElse(fa)(onFailure)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment