Scala Programming Syntax Examples


Hello World Program

object HelloWorld {
	def main(args: Array[String]): Unit = {
	println("Hello, World!")
	}
}

Output:

Variables

Mutable:

object Main {
	def main(args: Array[String]): Unit = {
	
          var x = 100;
	  x = 150;
	  println(x);
    
	}
}

Output:

Immutable:

object Main {
	def main(args: Array[String]): Unit = {
	
    val x = 100;
	  x = 150;
	  println(x);
    
	}
}

// This code will give an error because the variable is immutable

Output:

Mentioning data types along with variables:

object Main {
	def main(args: Array[String]): Unit = {
	
          var x: Int = 100;
	  x = 150;
	  println(x);
    
	}
}

Output:

Reading Input From the Console in Scala

object Main {
    def main(args: Array[String]): Unit = {

        var myName =  scala.io.StdIn.readLine()
        var myNumber =  scala.io.StdIn.readLine().trim.toInt

        println(myName, myNumber)
    
	}
}

Output:

Conditional Statements

If-Else statements:

object Main {
	def main(args: Array[String]): Unit = {

            var x: Int = 100;
	
  	    if(x>80){
  	      println("x is greater than 80")
  	    } else if(x==80){
  	      println("x is equal to 80")
  	    } else{
  	      println("x is less than 80")
  	    }
    
	}
}

Output:

Match-case Statements (Pattern Matching):

object Main {
	def main(args: Array[String]): Unit = {

          var x: Int = 1;
	
	  x match{
	    case 1 => println("x is 1")
	    case 2 => println("x is 2")
	    case 3 => println("x is 3")
	  }
    
	}
}

Output:

Loops

While Loop:

object Main {
    def main(args: Array[String]): Unit = {

        var x: Int = 1;
	
        while(x<=5){
            println(x);
            x = x+1;
        }
    
	}
}

Output:

For Loop:

object Main {
    def main(args: Array[String]): Unit = {

        for(i <- 1 to 10){
	        println(i)
	      }
    
	}
}

Output:

For loop – using until:

object Main {
    def main(args: Array[String]): Unit = {

        for(i <- 1 until 10){
	        println(i)
	      }
    
	}
}

Output:

Breaking a loop in scala:

import scala.util.control.Breaks._

object Main {
    def main(args: Array[String]): Unit = {

        breakable{
    	    for(i <- 1 until 10){
    	        if(i==5){
    	            break
    	        }
    	        println(i)
    	    }
        }
    
    }
}

Output:

String interpolation in Scala

object Main {
    def main(args: Array[String]): Unit = {

        var name = "John";
        var age = 23;
  
        println(name + " is " + age + " years old")
  
        //s-type
        println(s"$name is $age years old")
  
        //f-type
        println(f"$name%s is $age%d years old")
  
        //raw-type
        println(raw"Hello \n World")
    
    }
}

Output:

Functions in Scala

object Main {
    def main(args: Array[String]): Unit = {

        def addNumbers(x:Int, y:Int): Int ={
            return x+y
        }
  
        println(addNumbers(5,3))
    
    }
}

Unit means that the function doesn’t return anything.

Output:

Anonymous functions

object Main {
    def main(args: Array[String]): Unit = {

        var add = (x:Int,y:Int) => x+y;
        println(add(51,13));
    
    }
}

Output:

Higher Order functions

object Main {
    def main(args: Array[String]): Unit = {

        def math(x:Int,y:Int,f:(Int,Int)=>Int):Int = f(x,y);

        //addition
        val result1 = math(50,20,(x,y)=>x+y);
        println(result1);
    
       //subtraction
        val result2 = math(50,20,(x,y)=>x-y);
        println(result2);
    
    }
}

Output:

Function literals

object Main {
    def main(args: Array[String]): Unit = {

        var sum = (x:Int,y:Int) => x+y;
        println(sum(3,5))
    
    }
}

Output:

Partially applied functions

object Main {
  def main(args: Array[String]): Unit = {
    
        val sum = (a:Int, b:Int, c:Int) => a+b+c;
    
        val f = sum(10,20,_:Int);
    
        println(f(100));;
    
  }
}

Output:

Arrays

object Main {
    def main(args: Array[String]): Unit = {

        // Defining an array
        var myArray = new Array[Int](5);
      
        // Defining an array with data type
        var myArray2:Array[Int] = new Array[Int](5);
      
        // Initializing values
        var myArray3 = Array(1,2,3,4,5)

        // Accessing elements
        println(myArray3(0))

        // Looping
        for(i <- myArray3){
          println(i)
        }
    
    }
}

Output:

Lists

import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {

    // Initializing values
    var myList = List(1,8,5,6,9)

    // Accessing elements
    println(myList)

    // Looping
    for(i <- myList){
      println(i)
    }
    
  }
}

Output:

Sets

import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {

    // Initializing values
    val games = Set("Cricket","Football","Hocky","Golf")

    // Accessing elements
    println(games)

    // Looping
    for(i <- games){
      println(i)
    }
    
  }
}

Output:

Maps

object Main {
  def main(args: Array[String]): Unit = {
    
    // Creating an empty map
    var exampleMap = scala.collection.mutable.Map[String,Int]()


    // Creating a Map by initializing values
    var myMap = Map("A"->"Apple","B"->"Ball")

    // Accessing elements
    println(myMap)
    println(myMap("A"))

    // Adding & deleting values
    myMap += "C" -> "Cat"
    myMap -= "B"
    
    // Looping
    for((i,j) <- myMap){
      println(i,j)
    }
    
  }
}

Output:

Ashwin Joy

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts