Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8634793
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T09:48:30+00:00 2026-06-12T09:48:30+00:00

The following is a pretty common play framework 2 controller: def save(ideaId : Long)

  • 0

The following is a pretty common play framework 2 controller:

def save(ideaId : Long) = CORSAction { request =>
  Idea.findById(ideaId).map { idea =>
    request.body.asJson.map { json =>
      json.asOpt[Comment].map { comment =>
        comment.copy(idea = idea).save.fold(
          errors => JsonBadRequest(errors),
          comment => Ok(toJson(comment).toString)
        )
      }.getOrElse     (JsonBadRequest("Invalid Comment entity"))
    }.getOrElse       (JsonBadRequest("Expecting JSON data"))
  }.getOrElse         (JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))
}

I find it a bit annoying all those nested .maps, and I also find a bit tedious that each error handling is at the bottom

How would you improve it to make more readable, and, at the same time remain as functional idiomatic scala code?

I was thinking perhaps something like this (it’s seudo code, still does not compile)

def save(ideaId : Long) = CORSAction { request =>

  val idea = Idea.findById(ideaId).getOrElse(
    return JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))

  val json = request.body.asJson.getOrElse(
    return JsonBadRequest("Expecting JSON data"))

  val comment = json.asOpt[Comment].getOrElse(
    return JsonBadRequest("Invalid Comment entity"))

  comment.copy(idea = idea).save.fold(
    errors => JsonBadRequest(errors),
    comment => Ok(toJson(comment).toString)
  )

}

ps: I know It would be much better to avoid the return statement…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T09:48:31+00:00Added an answer on June 12, 2026 at 9:48 am

    First to simplify. Suppose I have three methods that take a String and return an Option[String]:

    def foo(s: String): Option[String] = if (s.size >= 4) Some(s + "1") else None
    def bar(s: String): Option[String] = if (s(0) != 'A') Some(s + "2") else None
    def baz(s: String): Option[String] = if (s toSet ' ') Some(s + "3") else None
    

    I want a method that pipes a string through these and returns the appropriate error message if I get a None along the way. I could write this:

    def all(s: String): Either[String, String] =
      foo(s).map { x =>
        bar(x).map { y =>
          baz(y).map { z =>
            Right(z)
          } getOrElse Left("Doesn't contain a space!")
        } getOrElse   Left("Starts with an A!")
      } getOrElse     Left("Too short!")
    

    But right, this isn’t pretty. We can use a for-comprehension and the toRight method on Option to write a much clearer version:

    def all(s: String): Either[String, String] = for {
      x <- (foo(s) toRight "Too short!"              ).right
      y <- (bar(x) toRight "Starts with an A!"       ).right
      z <- (baz(y) toRight "Doesn't contain a space!").right
    } yield z
    

    Calling toRight(msg) on an Option gives us a Left(msg) if it’s empty, and a Right(whatever) otherwise. We then have to take the right projection of the Either with .right, since Scala’s Either isn’t right-biased.

    The equivalent in your case would be something like this:

    def save(ideaId: Long) = CORSAction { request =>
      val saveResult = for {
        idea    <- (Idea.findById(ideaId) toRight "Could not find id"     ).right
        json    <- (request.body.asJson   toRight "Invalid Comment entity").right
        comment <- (json.asOpt[Comment]   toRight "Expecting JSON data"   ).right
        result  <- comment.copy(idea = idea).save().right
      } yield result
    
      saveResult.fold(
        error => JsonBadRequest(error),
        comment => Ok(toJson(comment).toString)
      )
    }
    

    Not quite as concise as your desired syntax, but the error messages appear in a more logical place, and we’ve gotten rid of the ugly nesting.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I thought the following would be a pretty common task and assumed there would
I've run into the following issue, which seems to be a pretty common one.
Following code is a pretty simple and complete JQuery Dialog. Everything works. Problem is
I'm pretty sure the following error is related to the fact that I'm sharing
I am using the following in my application DatePicker from jQuery UI Pretty Photo.
I'm currently in University and they're pretty particular about following their standards. They've told
The following method does its job but keeps printing a warning also, im pretty
This should be a pretty straightforward question. I have the following code, which forms
For some reason the following doesn't crash like my program does, but I'm pretty
I'm currently following: http://railsontherun.com/2007/10/04/sexy-charts-in-less-than-5-minutes/ I went through it all pretty easily, but then when

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.