发现scala里没有break和continue, 有时候实在是需要的话就要自己try catch异常,代码看起来有点蛋疼, 所以封装了一个可break和continue的foreach.
import scala.collection.TraversableLike
case class Breakable() {
def break: Unit = throw BreakException
def continue: Unit = throw ContinueException
def foreach(t: TraversableLike[_, _], op: Any => Unit): Unit = {
try {
t.foreach(i => {
try {
op(i)
} catch {
case ex: Exception =>
if (ex != ContinueException) throw ex
}
})
} catch {
case ex: Exception =>
if (ex != BreakException) throw ex
}
}
object BreakException extends Exception
object ContinueException extends Exception
}
使用
import com.myTest.util.Breakable
/**
* Created by Administrator on 2017/2/25 0025.
*/
object TestCode {
def main(args: Array[String]) {
val b = Breakable()
val a = List(1,2,3,4,5,6,7,8,9)
b.foreach(a, i => {
if(i == 5) b.continue
if(i == 7) b.break
println(i)
})
}
}
输出
1
2
3
4
6