Instruction break en Scala
Il n’y a pas d’instruction break en Scala par défaut, mais vous pouvez utiliser une autre méthode pour l’implémenter après Scala 2.8.breakinstruction. Lorsqu’elle est utilisée dans une boucle,breakinstruction, lorsqu’elle est exécutée, la boucle sera interrompue et le bloc de code après le corps de la boucle sera exécuté.
Syntaxe
La syntaxe de break en Scala est un peu différente, le format est le suivant :
// 导入以下包
import scala.util.control._
// 创建 Breaks 对象
val loop = new Breaks;
// 在 breakable 中循环
loop.breakable{
// 循环
for(...){
....
// 循环中断
loop.break;
}
}
Organigramme

Exemple
import scala.util.control._
object Test {
def main(args: Array[String]) {
var a = 0;
val numList = List(1,2,3,4,5,6,7,8,9,10);
val loop = new Breaks;
loop.breakable {
for( a <- numList){
println( "Value of a: " + a );
if( a == 4 ){
loop.break;
}
}
}
println( "After the loop" );
}
}
La sortie de l'exécution du code ci-dessus est :
$ scalac Test.scala $ scala Test Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4 After the loop
Interruption de boucles imbriquées
L’exemple suivant montre comment interrompre des boucles imbriquées :
import scala.util.control._
object Test {
def main(args: Array[String]) {
var a = 0;
var b = 0;
val numList1 = List(1,2,3,4,5);
val numList2 = List(11,12,13);
val outer = new Breaks;
val inner = new Breaks;
outer.breakable {
for( a <- numList1){
println( "Value of a: " + a );
inner.breakable {
for( b <- numList2){
println( "Value of b: " + b );
if( b == 12 ){
inner.break;
}
}
} // 内嵌循环中断
}
} // 外部循环中断
}
}
La sortie de l'exécution du code ci-dessus est :
$ scalac Test.scala $ scala Test Value of a: 1 Value of b: 11 Value of b: 12 Value of a: 2 Value of b: 11 Value of b: 12 Value of a: 3 Value of b: 11 Value of b: 12 Value of a: 4 Value of b: 11 Value of b: 12 Value of a: 5 Value of b: 11 Value of b: 12Autres extensions
Boucles Scala