1、scala中跳出循环语句的3种方法

  1)基于Boolean类型的控制变量

1 // while循环
 2 
 3 var flag = true
 4 var result = 0
 5 var n = 0
 6 
 7 while(flag) {
 8   res += n
 9   n += 1
10   println("res = "+ res)
11   println("n = "+ n)
12   if (n == 10) {
13     flag = false
14   }
15 }

 

1 // for循环
 2 
 3 var flag = true
 4 var res = 0
 5 
 6 for (i <- 0 until 10 if flag) {
 7   res += i
 8   println("res = " + res )
 9   if (i == 5) flag = false
10 }

  2)使用嵌套函数以及return

1 /**
 2     * 1 + 2 + 3 + 4
 3     *
 4     * @return
 5     */
 6   def addOuter() = {
 7     var res = 0
 8     def addInner() {
 9       for (i <- 0 until 10) {
10         if (i == 5) {
11           return
12         }
13         res += i
14         println("res = " + res)
15       }
16     }
17     addInner()
18     res
19   }
20 
21   def main(args: Array[String]): Unit = {
22     addOuter()
23   }

  3)使用Breaks类的break方法

def main(args: Array[String]): Unit = {
    // 需要导入这个包
    import scala.util.control.Breaks._
    var res = 0
    breakable {
      for (i <- 0 until 10) {
        if (i == 5) {
          break
        }
        res += i
      }
    }
    println("res = " + res)
  }