Skip to content

Instantly share code, notes, and snippets.

@dkomanov
Created January 9, 2016 18:32
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 dkomanov/b3cb5b0b536a62b090eb to your computer and use it in GitHub Desktop.
Save dkomanov/b3cb5b0b536a62b090eb to your computer and use it in GitHub Desktop.
[scala] result code: either with some implicits 2
import scala.language.implicitConversions
import scala.util.Try
package object business {
implicit final class ModelOrResultFromOption[M](private val opt: Option[M])
extends AnyVal {
// converts Option to Either.RightProjection
def orResult[R](result: => R) =
opt.fold[Either[R, M]](Left(result))(Right(_)).right
}
implicit final class ModelOrResultFromTry[M](private val opt: Try[M])
extends AnyVal {
// converts Try to Either.RightProjection
def orResult[R](result: => R) =
(if (opt.isFailure) Left(result) else Right(opt.get)).right
}
implicit def toResult[R](e: Either[R, R]): R =
e.fold(identity, identity)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment