Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you write this java code in (idiomatic) scala?

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;
}
like image 392
Slava Schmidt Avatar asked Nov 29 '22 05:11

Slava Schmidt


2 Answers

I think you'd try to avoid setting up the problem this way to begin with, but if that's what you had to deal with, I think the clearest 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
)
like image 188
Rex Kerr Avatar answered Dec 05 '22 09:12

Rex Kerr


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 always with Scalaz, it's a real shame that scala's type inference cannot infer partially-applied type constructors. Then you'd have:

(ps ∘∘ test) collect { case (i, true) => i } headOption orZero
like image 34
oxbow_lakes Avatar answered Dec 05 '22 11:12

oxbow_lakes