Created
November 25, 2014 17:00
-
-
Save rodolfo42/5ad3e03bab1485bb5bcc to your computer and use it in GitHub Desktop.
Try vs Either
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
// 1: Handler | |
def handle(req: Request): Response = { | |
val indexes = req.get("indexes") | |
service(indexes) | |
.map(Response(json(_))) | |
.orElse(Response.badRequest) | |
} | |
// 2: Service | |
def apply(indexes: Seq[Int]) = { | |
for { | |
index <- indexes | |
} yield getDataAtIndex(index) match { | |
case Right(result) => Right(process(result)) | |
case Left(ex) => Left(ex) | |
} | |
} | |
def process(data: Int): Result = Result(data) | |
// 3: Low-level API | |
def getDataAtIndex(index: Int) = { | |
index match { | |
case 0 => Left(new Exception("not be zero")) | |
case > 10 => Left(new Exception("not be 10")) | |
case i => Right(identity(i)) | |
} | |
} |
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
// 1: Handler | |
def handle(req: Request): Response = { | |
val indexes = req.get("indexes") | |
service(indexes) | |
.map(Response(json(_))) | |
.orElse(Response.badRequest) | |
} | |
// 2: Service | |
def apply(indexes: Seq[Int]) = { | |
for { | |
index <- indexes | |
data <- getDataAtIndex(index) | |
} yield process(data) | |
} | |
def process(data: Int): Result = Result(data) | |
// 3: Low-level API | |
def getDataAtIndex(index: Int) = Try { | |
index match { | |
case 0 => throw new Exception("not be zero") | |
case > 10 => throw new Exception("not be 10") | |
case i => identity(i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment