一、采用 Scala 自带的函数,退出循环
1 package com.atguigu.break
2
3 object TestBreak {
4 import scala.util.control.Breaks
5 def main(args: Array[String]): Unit = {
6 Breaks.breakable(
7 for (elem <- 1 to 10) {
8 println(elem)
9 if (elem == 5) Breaks.break()
10 }
11 )
12 println("正常结束循环")
13 }
14 }
二、 对 break 进行省略
1 package com.atguigu.break
2 import scala.util.control.Breaks._
3 object TestBreak2 {
4 def main(args: Array[String]): Unit = {
5 breakable {
6 for (elem <- 1 to 10) {
7 println(elem)
8 if (elem == 5) break
9 }
10 }
11 println("正常结束循环")
12 }
13 }