本文共 1772 字,大约阅读时间需要 5 分钟。
scala自身是没有continue,break这两个语法关键词的。 但是实际上我们还是很希望有这两个语法,那么我们是否可以自己实现呢?
scala自身是没有continue,break这两个语法关键词的。
但是实际上我们还是很希望有这两个语法,那么我们是否可以自己实现呢?
A class that can be instantiated for the break control abstraction. Example usage:
val mybreaks = new Breaksimport mybreaks.{break, breakable}breakable { for (...) { if (...) break() }}
Calls to break from one instantiation of Breaks will never target breakable objects of some other instantiation.
Breaks
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) } } } }}
输出结果
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
参考资料: http://www.cnblogs.com/rollenholt/p/4119105.html
A class that can be instantiated for the break control abstraction. Example usage:
Calls to break from one instantiation of
Breaks
will never target breakable objects of some other instantiation.输出结果
Hello Worldhello1hello2hello3hello4hello5the index is :6hello7hello8hello9hello10Process finished with exit code 0或者
输出结果
Hello World
hello1hello2hello3hello4hello5the index is :6参考资料: http://www.cnblogs.com/rollenholt/p/4119105.html