How could you write this Java (idiomatic) scala code?

int increment = 0; if (StringUtils.isNotBlank(request.getParameter(NEXT_SCREEN_PARAMETER_NAME))) { increment = 1; } else if (StringUtils.isNotBlank(request.getParameter(PREV_SCREEN_PARAMETER_NAME))) { increment = -1; } else if (StringUtils.isNotBlank(request.getParameter(LAST_SCREEN_PARAMETER_NAME))) { increment = Integer.MAX_VALUE; } 
+4
source share
4 answers

I think that you will try to avoid posing the problem in such a way as to start, but if this is what you had to deal with, I think the best thing would be something like

 def testParam(s: String) = StringUtils.isNotBlank(request.getParameter(s)) val increment = ( if (testParam(NEXT_SCREEN_PARAMETER_NAME)) 1 else if (testParam(PREV_SCREEN_PARAMETER_NAME)) -1 else if (testParam(LAST_SCREEN_PARAMETER_NAME)) Int.MaxValue else 0 ) 
+12
source
 val ps = Seq(1 -> NEXT_SCREEN_PARAMETER_NAME, -1 -> PREV_SCREEN_PARAMETER_NAME, Int.MaxValue -> LAST_SCREEN_PARAMETER_NAME) val test = StringUtils.isNotBlank(request.getParameter(_ : String)) (ps.view map { case (i,n) => i -> test(n) }) collect { case (i, true) => i } headOption getOrElse 0 

Using scalaz, you can use the map map (∘∘) function:

 ps.∘∘[PartialApply1Of2[Tuple2, Int]#Apply, String, Boolean](test) collect { case (i, true) => i } headOption orZero 

As with Scalaz, this is a real shame that scala type inference cannot invoke partially applied type constructors. Then you will have:

 (ps ∘∘ test) collect { case (i, true) => i } headOption orZero 
+4
source

You can do something like:

 val conditions = Seq((NEXT_SCREEN_PARAMETER_NAME,1), (PREV_SCREEN_PARAMETER_NAME,-1), (LAST_SCREEN_PARAMETER_NAME,Integer.MAX_VALUE)) def parameterDefined(p: String) = StringUtils.isNotBlank(request.getParameter(p)) val increment = conditions.find(x => parameterDefined(x._1)).map(_._2).getOrElse(0) 

This determines the correct increment value for each parameter, finds the first parameter specified, retrieves the increment value, giving 0 if no match is found.

+3
source

Slightly modified version of Jeff's request

 object ScreenParam { def unapply(kv:Tuple2[String, Int]) = if(StringUtils.isNotBlank(request.getParameter(kv._1))) Some(kv._2) else None } val conditions = Seq((NEXT_SCREEN_PARAMETER_NAME,1), (PREV_SCREEN_PARAMETER_NAME,-1), (LAST_SCREEN_PARAMETER_NAME,Integer.MAX_VALUE)) conditions.collect{ case ScreenParam(value) => value}.getOrElse(0) 
+3
source

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


All Articles