2010-12-23 51 views
4
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; 
} 

回答

12

我想你会尽量避免这种方式来开始建立的问题,但如果这是你不得不处理什么,我觉得最明显的将是这样

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 
) 
+0

`def testParam(s:String)= StringUtils.isNotBlank(request.getParameter(s)) - nice! – 2010-12-23 15:43:40

+0

@Fabian - 你的回答也非常明智,如果我见过你的话,我就不会加入我的答案。 (我输入了我的名字,然后必须去AFK,然后在我回来时点击发送。) – 2010-12-23 16:35:22

3

你可以这样做:

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) 

这定义了适当的增加值对每个参数,找到的第一个定义的参数,如果没有找到匹配提取增值收益0。

3

略体改版本杰夫的ansver的

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) 
4
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 

使用scalaz,您可以使用地图(∘∘)功能:

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

和Scalaz一样,scala的类型推断不能推断部分应用类型的构造函数是一个真正的耻辱。然后你会有:

(ps ∘∘ test) collect { case (i, true) => i } headOption orZero 
相关问题