Let's look at a loop in Java:
for (int i = 1; i < 4; i++) { + ",");}
There is no doubt that Scala can make this loop more concise. According to the previous section, it is not necessary to display the type of the specified variable i, and we do not even need to declare the variable. The next output statement can be more concise, and in Scala you can use the println () method to output a string directly. Finally, Scala's looping structure is also very lightweight. OK, let's take a look at the code:
for (I <-1 to 3) { + ",")}
In the loop structure of the above code, the left side of the arrow (<-) is a Val (note not var) variable, and the right side is a generator expression. A new Val variable i is created in each loop, initialized with successive values produced by the generator expression.
The successive values generated by the generator expression "1 to 3" contain the Nether [1] and upper bound [3], and if you replace the to method with the until method, you can exclude the upper bound.
Both to and until are Scala's methods of the Richint class, and calling 1 to 3 is equivalent to 1.to (3), but the former is more elegant. In Scala, if the method has 0 or 1 parameters, the dots and parentheses can be discarded. If the method has more than one argument, the parentheses must be preserved, but the point is still optional. Another example of a very common expression in Java: 1 + 2 in Scala is actually 1.+ (2), and + is a method rather than a simple symbol.
We already know that 1 to 3 returns a continuous value (range), so you can consider using the Foreach method of range to implement loops. The code is as follows:
(1 to 3). foreach (I-= print (i + ","))
foreach is a method of the range class that takes a function value as an argument. So to provide a function code in parentheses to accept an argument. In this case, the argument is I. the arrow "= =" is the function of separating the left argument list from the right function implementation.
Scala learns the loops in 2-scala