Scala Newb
Scala Newb

Reputation: 281

More functional and concise way to write this in Scala

I started with this (in a Play Action method):

    val foo = JPA.em.find(classOf[Foo], id)
    if (foo == null) NotFound("Bad Id") else Ok(Json.toJson(foo))

not like its imperativeness, I went to this:

    Option(JPA.em.find(classOf[Foo], id)) match {
      case Some(foo) => Ok(Json.toJson(foo))
      case None => NotFound("Bad Id")
    }

more functional, but longer.

I apologize for the very general nature of the question but I bet the answers could be helpful to many.

Upvotes: 1

Views: 182

Answers (2)

Ben James
Ben James

Reputation: 125119

It's definitely worth wrapping unsafe Java APIs like this with some reusable methods that return Options, for example

def findOpt[T](cls: Class[T], id: Object): Option[T] =
  Option(JPA.em.find(cls, id))

Consuming this API, instead of using JPA directly, means that you don't need to worry about null checks elsewhere in your code. It's all dealt with in one place.

Now, you can decide whether to use match, or fold, or map/getOrElse; what's important is that the possible absence of a result is represented in the type of findOpt.

findOpt(classOf[Foo], id) map (foo => OK(Json.toJson(foo)) getOrElse NotFound("Bad Id")

Upvotes: 1

sksamuel
sksamuel

Reputation: 16387

Option(JPA.em.find(classOf[Foo], id)).map(foo=>Ok(Json.toJson(foo))).getOrElse(NotFound("Bad Id"))

Upvotes: 4

Related Questions