Last active
August 29, 2015 14:01
-
-
Save nicholasren/f061c4c5f76c562e01ff to your computer and use it in GitHub Desktop.
scala training example - monad
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
//in post controller | |
User user = null; | |
try { | |
user = userService.findById(userId) | |
} catch (UserNotFoundException e) { | |
throw //handling exception | |
} | |
List<Post> posts; | |
if(user != null) { | |
try { | |
posts = postService.findByUser(user) | |
} catch (PostNotFoundException e) { | |
//handling exception | |
} catch (PostDeletedException e) { | |
//handling exception | |
} | |
} | |
//render result page with posts |
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
// Try[T] is monad | |
case class Try[T] | |
case class Success[T] extends Try[T] | |
case class Failure[T] extends Try[T] | |
// in post controller | |
//String => Try[User] | |
val user: Try[User] = userService.findById(userId) | |
// User => Try[List[Post]] | |
val posts: Try[List[Post] = postService.findByUser(user) | |
posts match { | |
case Success(p) => render(p) | |
case Failure(e) => error(e) | |
} | |
//String => Try[List[Post] | |
val posts: Try[List[Post]] = userService.findById(userId).map{ user => postService.findByUser(user)} | |
posts match { | |
case Success(p) => render(p) | |
case Failure(e) => error(e) | |
} | |
//note: go out of monad is dangerous!!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment