Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Option values in Scala

Tags:

scala

I am parsing three request parameters, all of which are wrapped in an Option type. If any of these Options are None, then I want to return a 400 error. How do I check if any of these return values are of type None?

like image 637
jcm Avatar asked Oct 06 '14 11:10

jcm


2 Answers

Why not just like this?

if (o1.isEmpty || o2.isEmpty || o3.isEmpty) BadRequest("Foo")

Alternativeley depending on your implementation you might have your options in some kind of collection. Then you could use exists

if (parsedRequestParameters.exists(_.isEmpty)) BadRequest("Foo")

A third alternative you might like, in case you want to do something with the contents of your options:

val response = for {
  v1 <- o1
  v2 <- o2
  v3 <- o3
} yield <some response depending on the values of o1..o3>

response getOrElse BadRequest("something wasn't specified")
like image 135
Martin Ring Avatar answered Sep 19 '22 13:09

Martin Ring


Another possibility, added for completeness:

(o1, o2, o3) match {
  case(Some(p1), Some(p2), Some(p3)) => Ok // Do stuff with p1, p2, p3
  case _ => BadRequest
}
like image 20
Dominik Bucher Avatar answered Sep 20 '22 13:09

Dominik Bucher