Created
January 9, 2016 18:32
-
-
Save dkomanov/b3cb5b0b536a62b090eb to your computer and use it in GitHub Desktop.
[scala] result code: either with some implicits 2
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
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