zoukankan      html  css  js  c++  java
  • Scala 封装可break和continue的foreach循环

    发现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

  • 相关阅读:
    I Hate It
    满减优惠[Offer收割]编程练习赛4
    积水的城市 hiho[Offer收割]编程练习赛4
    Subsequence 尺取法
    526. 优美的排列
    401. 二进制手表
    306. 累加数
    216. 组合总和 III
    131. 分割回文串
    ubuntu deepin-软件 分辨率的问题
  • 原文地址:https://www.cnblogs.com/drwong/p/6617583.html
Copyright © 2011-2022 走看看