Created
July 19, 2015 20:20
-
-
Save joecwu/574c1f213bbb62a52ba7 to your computer and use it in GitHub Desktop.
Blog Scalaz - Either http://blog.joecwu.com/2015/07/scava-scala-scalaz-either.html
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
case class Error(code:Int, msg:String) | |
case class User(id:String,name:String) | |
object UserRepo{ | |
def find(id:String) : Option[User] = {None} | |
def getUser(id:String) : Either[Error,User] = { | |
find(id).map(Right(_)).getOrElse(Left(Error(404,s"User not found. id:[$id]"))) | |
} | |
} | |
object TestApp { | |
def run = { | |
UserRepo.getUser("testId") match { | |
case Right(user) => println("got User!") | |
case Left(err) => println(s"err code:[${err.code}] msg:[${err.msg}]") | |
} | |
} | |
} |
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
case class Error(code:Int, msg:String) | |
case class User(id:String,name:String) | |
object UserRepo{ | |
def find(id:String) : Option[User] = {id!="0" option User(id,"YOYO")} | |
def getUser(id:String) : Error\/User = { | |
find(id).map(_.right).getOrElse(Error(404,s"User not found. id:[$id]").left) | |
} | |
} | |
object TestApp { | |
def run = { | |
val user = UserRepo.getUser("user") | |
user match { | |
case \/-(user) => println("got User!") | |
case -\/(err) => println(s"err code:[${err.code}] msg:[${err.msg}]") | |
} | |
// got User! | |
for{ | |
user1 <- UserRepo.getUser("user1") | |
user2 <- UserRepo.getUser("user2") | |
user3 <- UserRepo.getUser("0") | |
}yield{ | |
List(user1,user2,user3) | |
} | |
// scalaz.\/[Error,(User, User, User)] = -\/(Error(404,User not found. id:[0])) | |
for{ | |
user1 <- UserRepo.getUser("user1") | |
user2 <- UserRepo.getUser("user2") | |
user3 <- UserRepo.getUser("user3") | |
}yield{ | |
List(user1,user2,user3) | |
} | |
// scalaz.\/[Error,List[User]] = \/-(List(User(user1,YOYO), User(user2,YOYO), User(user3,YOYO))) | |
UserRepo.getUser("user1").map{user => user.id} | |
// scalaz.\/[Error,String] = \/-(user1) | |
UserRepo.getUser("0").getOrElse(User("DefaultUser","YA")) | |
// User = User(DefaultUser,YA) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment