Home »
Scala language
Code blocks In Scala
Scala code block: Code block is multiple lines of code that have only one entry and one exit point. In this Scala code block tutorial, we will learn about code block in Scala, their usage and working example code.
Submitted by Shivang Yadav, on July 14, 2019
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.
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.