Scala Code Blocks

In this tutorial, we will learn about the code blocks in Scala, their usage with examples. Submitted by Shivang Yadav Last updated : April 02, 2023

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: Scala program to demonstrate the code block

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 of Scala code blocks

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: Scala program to demonstrate the nesting of code blocks

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.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.