zoukankan      html  css  js  c++  java
  • Scala:没有continue,break怎么办?

    scala自身是没有continue,break这两个语法关键词的。

    但是实际上我们还是很希望有这两个语法,那么我们是否可以自己实现呢?

    • 从官网上搜索,我们可以找到一下关于break的类相关资料:

    Breaks extends AnyRef

    A class that can be instantiated for the break control abstraction. Example usage:

    val mybreaks = new Breaks
    import mybreaks.{break, breakable}
    
    breakable {
      for (...) {
        if (...) break()
      }
    }
    

    Calls to break from one instantiation of Breaks will never target breakable objects of some other instantiation.

    • continue测试:
    import util.control.Breaks._
    
    /**
      * Created by Administrator on 2016/11/15.
      */
    object MyMain {
      def main(args: Array[String]): Unit = {
        println("Hello World")
    
        for (index <- 1 to 10) {
          breakable {
            if (index == 6) {
              println("the index is :"+index)
              break()
            }
            else {
              println("hello" + index)
            }
          }
        }
      }
    }
    

     输出结果
    Hello World
    hello1
    hello2
    hello3
    hello4
    hello5
    the index is :6
    hello7
    hello8
    hello9
    hello10

    Process finished with exit code 0

    • break测试:
    import util.control.Breaks._
    
    /**
      * Created by Administrator on 2016/11/15.
      */
    object MyMain {
      def main(args: Array[String]): Unit = {
        println("Hello World")
        breakable {
          for (index <- 1 to 10) {
            if (index == 6) {
              println("the index is :" + index)
              break()
            }
            else {
              println("hello" + index)
            }
          }
        }
      }
    }
    

     或者

    import util.control.Breaks._
    
    /**
      * Created by Administrator on 2016/11/15.
      */
    object MyMain {
      def main(args: Array[String]): Unit = {
        println("Hello World")
        for (index <- 1 to 10) {
          if (index == 6) {
            println("the index is :" + index)
            break
          }
          else {
            println("hello" + index)
          }
        }
      }
    }
    

     输出结果

    Hello World
    hello1
    hello2
    hello3
    hello4
    hello5
    the index is :6

    参考资料:scala break & continue http://www.cnblogs.com/rollenholt/p/4119105.html

  • 相关阅读:
    gRPC框架详解
    从零开始的Python #3
    从零开始的Python #2
    从零开始的Python #1
    【摸鱼on牛客】2020ICPC 小米 网络选拔赛第一场
    【gym摸鱼实录】2020 Lenovo Cup USST Campus Online Invitational Contest
    P1452 [USACO03FALL]Beauty Contest G
    HDU1115 Lifting the Stone
    使用jdbc操作ClickHouse
    DbVisualizer 9.2.14 安装教程
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/6079688.html
Copyright © 2011-2022 走看看