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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM