Scala - 在 try-catch 块中跳出循环
Scala - Breaking out of a loop in a try-catch block
我有以下 Scala 代码:
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
}
}
}
}
是 if (booleanVal) break
不起作用,因为 Scala 似乎让它作为例外工作。如何跳出这个嵌套循环?
将 if (booleanVal) break
移出 try 块:
val booleanVal = try {
getBoolean(file)
} catch {
case e: Throwable => //do something
}
if (booleanVal) break // break out of the try/catch + both loops
我建议你不要使用 break,首先这是丑陋的 :) 其次,这是不可读的。
也许你会喜欢这样的东西:
for {
anotherFile <- someFile
file <- anotherFile
b <- Try(getBoolean(file))
if(b)
} /// do something
如果需要在try块中做更多的工作,可以这样写:
for {
anotherFile <- someFile
file <- anotherFile
} Try{ if(!getBoolean(file)) /* */ } match {
case onSuccess(v) =>
case onFailure(e: Throwable) =>
}
我有以下 Scala 代码:
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
}
}
}
}
是 if (booleanVal) break
不起作用,因为 Scala 似乎让它作为例外工作。如何跳出这个嵌套循环?
将 if (booleanVal) break
移出 try 块:
val booleanVal = try {
getBoolean(file)
} catch {
case e: Throwable => //do something
}
if (booleanVal) break // break out of the try/catch + both loops
我建议你不要使用 break,首先这是丑陋的 :) 其次,这是不可读的。 也许你会喜欢这样的东西:
for {
anotherFile <- someFile
file <- anotherFile
b <- Try(getBoolean(file))
if(b)
} /// do something
如果需要在try块中做更多的工作,可以这样写:
for {
anotherFile <- someFile
file <- anotherFile
} Try{ if(!getBoolean(file)) /* */ } match {
case onSuccess(v) =>
case onFailure(e: Throwable) =>
}