0

I have the following Scala code:

breakable {
  someFile.foreach { anotherFile =>
    anotherFile.foreach { file =>
      try {
        val booleanVal = getBoolean(file)
        if (booleanVal) break //break out of the try/catch + both loops
      } catch {
        case e: Throwable => //do something
      }
    }
  }
}

it's the if (booleanVal) break that doesn't work, because it seems like Scala makes it work as an exception. How do I break out of this nested loop?

averageUsername123
  • 725
  • 2
  • 10
  • 22

2 Answers2

1

Move if (booleanVal) break out of try block:

val booleanVal = try { 
  getBoolean(file)
} catch {
  case e: Throwable => //do something
}
if (booleanVal) break // break out of the try/catch + both loops
kostya
  • 9,221
  • 1
  • 29
  • 36
0

I suggest you to not use break, for the first this is ugly :) and the second, this is unreadable. Maybe you would like something like this:

for {
  anotherFile <- someFile
  file <- anotherFile
  b <- Try(getBoolean(file))
  if(b)
} /// do something

If you need to do more work in the try block, you can write:

for {
    anotherFile <- someFile
    file <- anotherFile
} Try{ if(!getBoolean(file)) /* */ } match {
  case onSuccess(v) =>
  case onFailure(e: Throwable) =>
}