pal
pal

Reputation: 105

How to break/escape from a for loop in Scala?

Im new to scala and searched a lot for the solution. I'm querying the database and storing the value of the http request parsed as a json4s object in response. I wait for the response and parse the json.

val refService = url("http://url//)
val response = Http(refService OK dispatch.as.json4s.Json)
var checkVal :Boolean = true
val json = Await.result(response, 30 seconds)

val data = json \ "data"

I want to run a loop and check if the value of "name" is present in the data returned. If present I want to break and assign checkVal to false. So far I have this:

for {
  JObject(obj) <- data
 JField("nameValue", JString(t)) <- obj //nameValue is the column name in the returned data
  } yield {checkVal= if (t == name){ break }
 else 
   true
  }

Eclipse is giving me the following error: type mismatch; found : List[Unit] required: List[String] Please advice. Thank you.

Upvotes: 1

Views: 5315

Answers (3)

Puneeth Reddy V
Puneeth Reddy V

Reputation: 1568

I would suggest to use exists as it is lazy on all collection members.

code:-

val list= Map(
        "nameValue1" -> 1,
        "nameValue2" -> 2,
        "nameValue3" -> 3,
        "nameValue4" -> 4,
        "nameValue5" -> 5
        )
val requiredHeader = "nameValue2"
var keyvalue:Int=0
list.exists(p=>{ if(p._1.equalsIgnoreCase(requiredHeader))keyvalue=p._2;p._1.equalsIgnoreCase(requiredHeader) })

if(keyvalue!=0){
        //header present
}else{
        //header doesn't exit
}

Upvotes: 0

ka4eli
ka4eli

Reputation: 5424

One of your problems is that you have different return types in yield: if t==name, return type is the type of break, and if t!=name return type is Boolean. In scala you don't have break operator, this behaviour is achieved using breakable construct and calling break() method which actually throws an exception to exit from breakable block. Also you can use if statements in for body to filter you results:

import scala.util.control.Breaks._

breakable {
  for {
    JObject(obj) <- data
    JField("nameValue", JString(t)) <- obj
    if t == name
  } yield {
    checkVal = false
    break()
  }
}

UPDATE: I used this imperative approach because you are new to scala, but it's not scala way. IMHO you should stick to @Imm code in comments to your question.

Upvotes: 2

Lionel Port
Lionel Port

Reputation: 3542

I actually don't like using pattern matching in for loops as if for some reason data is not a JObject it won't be handled well. I prefer an approach like below.

data match {
  case JObject(fields) => fields.exists{
    case (name:String,value:JString) => name == "nameValue" && value.s == "name"
    case _ => false
  }
  case _ => false // handle error as not a JObject
}

Edit: revised to include your matches.

Upvotes: 0

Related Questions