Java是指令式風格,Scala是函數式風格。函數
在Scala中,應該儘可能適用循環,而是應用函數的方式來處理。oop
Scala並無提供break和continue語句來退出循環,那麼若是咱們又確實要怎麼辦呢,有以下幾個選項:spa
1. 使用Boolean型的控制變量。code
2. 使用嵌套函數,從函數當中return對象
3. 使用Breaks對象中的break方法(這裏的控制權轉移是經過拋出和捕獲異常完成的,儘可能避免使用這套機制)blog
4. 遞歸函數重寫循環遞歸
import util.control.Breaks._ object LoopOps { def main(args: Array[String]) = { val list = List(21, 214, -4352, 65436, 7534) breakTest1(list) breakTest2(list) contniueTest1(list) continueTest2(list) continueTest3(list) } def breakTest1(list: List[Int]) = { println("breakable語句塊來實現break操做") breakable { for (elem <- list) if (elem < 0) break else println(elem) } } def breakTest2(list: List[Int]) = { println("增長一個boolean變量做爲for循環守衛,while循環同理") var foundMinus = false for (elem <- list if !foundMinus) { if (elem < 0) foundMinus = true else println(elem) } } def contniueTest1(list: List[Int]) = { println("breakable語句塊來實現continue操做") for (elem <- list) breakable { if (elem < 0) break else println(elem) } } def continueTest2(list: List[Int]) = { println("if else控制來實現continue操做") for (elem <- list) if (elem < 0) () else println(elem) } def continueTest3(list: List[Int]) = { println("遞歸函數重寫循環") def next(i: Int): Unit = { if (i >= list.size) Unit else if (list(i) < 0) next(i + 1) else println(list(i)); next(i + 1) } next(0) } }