Scala Foundation Course - Scala Loops


Welcome back. The next item on our list is the while loop.The while loop of Scala is a statement because it doesn't return a meaningful value. It always results in a Unit. The syntax is simple. Here is an example.

                                
    def loopN(i:Int) = {
        var j = 1
        while (j <= i){
            println(j)
            j = j + 1
        }
    }                                       
                         

Scala also supports a do while loop. It works same as while loop except that it checks the condition in the end. Here is an example.

                                
    def loopDo(i:Int) = {
        var j = 1
        do{
            println(j)
            j = j + 1
        }while(j <= i)
    }                                       
                         

A Pure functional programming language doesn't offer a while loop and the do-while loop. Scala keeps it there to support the Imperative approach as well. You can use while loop to implement an algorithm that repeats until a condition change. However, the functional approach is to use recursion for such requirements. That's all about while loop.


You will also like:


Scala Functions

Scala is a functional programming language. Functions are the building blocks in Scala.

Learning Journal

First Class Functions

Function is a first-class citizen in functional programming. What does it mean?

Learning Journal

Hadoop Security

Hadoop security implementation using Kerberos.

Learning Journal

Scala placeholder syntax

What is a scala placeholder syntax and why do we need it? Learn from experts.

Learning Journal

Spark in Google cloud

Learn How to Install Hadoop and Spark in Google Cloud in just 2 minuts.

Learning Journal