문제

I am trying to read input in scalatra webapp using for iteration in below manner

for (
         input1<- params.getOrElse("input1", "");
         input2 <- params.getOrElse("input2", "");
         search <- params.getOrElse("search", false)
    ) {
       //Perform action
    }

It is throwing error value foreach is not a member of Object.

In case if user doesn't provide any input, it should default empty string and call the action instead of breaking out of loop. For that reason i am using getOrElse. But i haven't succeeded.

Any help?

도움이 되었습니까?

해결책

You can use for-comprehensions to work with Option but you can't use it for objects that don't have at least one defined foreach, map or flatMap. In your case, if params is returning options then...

for(
  input1 <- params get "input1"
  input2 <- params get "input2"
 ){
   //do stuff
 }

Wherein this will not run if both input and input2 are not None.

If you don't want to short circuit the control logic and you want there to be sane defaults for Option returns, then a better way is just to do

 myFunction(params getOrElse ("input1", "default1"), params getOrElse ("input2", 42))

where you're explicitly providing the defaults and passing them into a function call.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top