Scala Learning three: looping
Scala Loop
Scala has for,while two forms
while loops in the same way as in Java, no longer repeating.
There's no Java in Scala.
for (variable fame; condition control; variable control)
Only
for (n <-1 to N)
//contains n values//
and for
(n <-1 until N)
//not containing n values
The Val,var is not required before the variable name in the Scala for loop. A type is a variable type in a collection. The scope is depressed and the loop ends.
There is no break in Scala, continue to exit, control loops.
Import Scala.util.control.breaks._
breakable {for
(...) {
if (...) {
break
}
}
}
The breakable must completely wrap the entire for loop block, otherwise it will not be able to exit the loop.
Break jumps out of the loop by throwing and catching exceptions. For high-time situations, use should be reduced. advanced for loop form:
Scala's for loop can have multiple generators in the form of variable <-expressions , separated by ";" between each generator
Scala code for
(outer <-1 to 3, inner <-1 to 3) {
println (TEN * outer + inner)
}
Java code
//Its function is equivalent to Java double-layer for loop for
(int outer = 1; outer <= 3; outer++) {for
(int inner = 1; inner <= 3; inner++) {
System.out.println (TEN * outer + inner)
}
}
For Loop Generator guard:
Scala code:
//Each generator can take a guard: for
(outer <-1 to 5 if outer% 2! = 0; inner <-1 to 5 if inner% 2 = 0) { C12/>PRINTLN (Ten * outer + inner)
}
Its role is equivalent to Java's double-layer for loop:
Java code: for
(int outer = 1; outer <= 5; outer++) {
if (outer% 2! = 0) {for
(int inner = 1; Inner <= 5 ; inner++) {
if (inner% 2 = = 0) {
System.out.println (TEN * outer + inner
)
}
}}}
You can also use any number of definitions to reference variables that you can use in a loop:
for (outer <-1 to 5; middle = 6-outer, inner <-Middle to 5) {
println (outer + inner)
}
For Yield:
If the For loop body starts with yield, the loop forms a collection, and each iteration produces a value in the collection
Val col = for (a < 1 to 5) yield {
"Word" + A
}
//Col is a collection: indexedseq[string]
The wrong notation if the collection is returned. Yield must follow the FOR loop expression.
For (a < 1 to 5) {
yield {
"Word" + A
}
}