首页 > 代码库 > Scala 封装可break和continue的foreach循环

Scala 封装可break和continue的foreach循环

发现scala里没有break和continue, 有时候实在是需要的话就要自己try catch异常,代码看起来有点蛋疼, 所以封装了一个可break和continue的foreach.

import scala.collection.TraversableLike

case class Breakable() {

  def break: Unit = throw new BreakException

  def continue: Unit = throw new ContinueException

  def foreach(t: TraversableLike[_, _], op: Any => Unit): Unit = {
    try {
      t.foreach(i => {
        try {
          op(i)
        }catch {
          case ex : Throwable =>
            if(!ex.isInstanceOf[ContinueException]) throw ex
        }
      })
    }catch {
      case ex : Throwable =>
        if(!ex.isInstanceOf[BreakException]) throw ex
    }
  }
  class BreakException extends Exception
  class 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

 

Scala 封装可break和continue的foreach循环