Skip to content

Instantly share code, notes, and snippets.

@nicholasren
Last active August 29, 2015 14:01
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 nicholasren/f061c4c5f76c562e01ff to your computer and use it in GitHub Desktop.
Save nicholasren/f061c4c5f76c562e01ff to your computer and use it in GitHub Desktop.
scala training example - monad
//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
// 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