Skip to main content

Command Palette

Search for a command to run...

Lesson 1: Scala Programming Language Tutorial

Published
2 min read

Lesson 1: Scala Programming Language Tutorial


Example 1: Hello, World! in Scala

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

Explanation:

  1. object HelloWorld – Defines an object named HelloWorld. In Scala, object is used for defining a singleton instance.

  2. def main(args: Array[String]): Unit = { – This is the main method, the entry point of a Scala program.

  3. println("Hello, World!") – Prints "Hello, World!" to the console using println.

  4. } – Closes the main method and HelloWorld object.


Example 2: Variables and Data Types

val name: String = "Scala"
var age: Int = 5
age = 6

Explanation:

  1. val name: String = "Scala" – Declares an immutable variable name of type String, storing "Scala".

  2. var age: Int = 5 – Declares a mutable variable age of type Int, initialized with 5.

  3. age = 6 – Modifies age since it is declared with var, allowing reassignment.

  4. val vs varval name is immutable, while var age can be changed.


Example 3: Functions in Scala

def add(x: Int, y: Int): Int = {
  x + y
}
println(add(3, 4))

Explanation:

  1. def add(x: Int, y: Int): Int = { – Defines a function add that takes two Int parameters and returns an Int.

  2. x + y – Performs addition of x and y and returns the result.

  3. } – Closes the function body.

  4. println(add(3, 4)) – Calls add(3, 4), printing 7 to the console.


Example 4: Looping with for

for (i <- 1 to 5) {
  println(s"Iteration: $i")
}

Explanation:

  1. for (i <- 1 to 5) – A for loop that iterates from 1 to 5 inclusive.

  2. { println(s"Iteration: $i") } – Inside the loop, prints the iteration number using string interpolation.

  3. s"Iteration: $i" – Uses s before the string to insert variable i dynamically.

  4. } – Closes the loop block.


This is Lesson 1 of Scala programming with basic examples and explanations.

More from this blog

Programming , Big Data, DevOps, etc

271 posts

Programming , Big Data, DevOps, etc