Scala代码块 (Scala code block)
Code Block is multiple lines of code that are enclosed between braces i.e. everything between { and } is in one block code.
代码块是括在大括号之间的多行代码,即{和}之间的所有内容都在一个块代码中 。
Block of code is generally used in methods, class definition, loop statements, and logic. You can use the block of code without them also but using like this is not a common practice.
代码块通常用于方法,类定义,循环语句和逻辑中。 您也可以在没有代码的情况下使用代码块,但是使用这种代码并不是一种常见的做法。
Syntax:
句法:
{
// statement 1
// statement 2
...
}
Example:
例:
object MyClass {
def adder(a:Int, b: Int) = a + b;
def main(args: Array[String]) {
print("sum of a and b is " + adder(225,140));
}
}
Output
输出量
sum of a and b is 365
Code explanation:
代码说明:
I have used this code to explain to you how to use a block of code and how things are defined in a single line? The object code is a block of code since it is inside a pair of { } braces. But, see to the method adder, this method is defined in a single line i.e it does not have any block of code. Similarly, the contents of the main methods are enclosed in a block of code.
我已使用此代码向您解释如何使用代码块以及如何在一行中定义事物? 目标代码是代码块,因为它位于一对{}括号内。 但是,请参见方法添加器,此方法在一行中定义,即它没有任何代码块。 同样,主要方法的内容包含在代码块中。
嵌套代码块 (Nesting block of code)
A block of code can be nested inside another block of code. i.e. block A inside block B, always block B is closed before Block A. This is commonly seen in nested loops, nested conditional statements, etc.
一个代码块可以嵌套在另一个代码块内。 也就是说,在块B中的块A,总是在块A之前关闭块B。这在嵌套循环,嵌套条件语句等中很常见。
Syntax:
句法:
{
// code block A
{
// Code Block B
}
}
Example:
例:
object MyClass {
def add(x:Int, y:Int) = x + y;
def main(args: Array[String]) {
var i,j=0
for(i <- 0 to 1){
for(j <- 0 until 2){
print(i+" "+j+"\n")
}
}
}
}
Output
输出量
0 0
0 1
1 0
1 1
Code explanation:
代码说明:
This code shows a nested for loops, one loop inside other, we treat each loop as a code block. The for loop with to first block and for loop with until is the second block. Each time the first block ends after the end of the second block.
这段代码显示了一个嵌套的for循环 ,一个循环在另一个循环内,我们将每个循环视为一个代码块。 for循环到第一个块,for循环到直到是第二个块。 每次第一个块在第二个块结束之后结束。
翻译自: https://www.includehelp.com/scala/code-blocks-in-scala.aspx