Multiple parameter values ​​in Scala

I am parsing three query parameters, all of which are wrapped in Option type. If any of these options is None , then I want to return a 400 error. How can I check if any of these return values ​​is of type None ?

+6
source share
5 answers

Why not just like that?

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

Alternativeley, depending on your implementation, you may have your options in some kind of collection. Then you can use exists

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

The third option that you might like if 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") 
+14
source

Another feature added for completeness:

 (o1, o2, o3) match { case(Some(p1), Some(p2), Some(p3)) => Ok // Do stuff with p1, p2, p3 case _ => BadRequest } 
+6
source

I prefer to work with them as a collection of Option [T]

 scala> Seq(Option(1), Option(5), None) res0: Seq[Option[Int]] = List(Some(1), Some(5), None) scala> val result = res0.exists(_.isEmpty) result: Boolean = true 
+2
source

For completeness on exists on the set Option we also consider forall as follows:

 val a = Array(Some(3), None, Some(7)) a.forall(_.nonEmpty) res: false a.forall(!_.isEmpty) res: false a.forall(_.isDefined) res: false 

and

 val b = Array(Some(3), Some(5), Some(7)) b.forall(_.nonEmpty) res: true b.forall(_.isDefined) res: true 
+1
source

You can also use zip, but it will wrap the underlying elements in Seq from nested pairs that are not easy to smooth out for reuse.

 Some(1) zip Some(2) == List((1,2)) Some(2) zip Some(2) zip Some(3) == List(((1,2),3)) Some(1) zip Some(2) zip None == List() 

or you can do something like this

 val options = Seq(Some(p1), Some(p2), Some(p3),None) val parameters = options.flatten if(parameters.length == options.length) do something with parameters 
0
source

Source: https://habr.com/ru/post/976293/


All Articles