Skip to main content

Command Palette

Search for a command to run...

Lesson 2: Scala Programming Language Tutorial

Published
2 min read

Lesson 2: Scala Programming Language Tutorial

Here are four Scala code examples, each with four explanation points, repeating the relevant code fragment inside each point.


Example 1: Conditional Statements (if-else)

val number = 10

if (number > 0) {
  println("Positive number")
} else {
  println("Negative number")
}

Explanation:

  1. val number = 10 – Declares an immutable variable number and assigns it the value 10.

  2. if (number > 0) { – Checks if number is greater than 0, executing the block inside if true.

  3. println("Positive number") – If number > 0, prints "Positive number".

  4. else { println("Negative number") } – If number is not greater than 0, prints "Negative number".


Example 2: Pattern Matching (match)

val day = 3

val result = day match {
  case 1 => "Monday"
  case 2 => "Tuesday"
  case 3 => "Wednesday"
  case _ => "Unknown"
}
println(result)

Explanation:

  1. val day = 3 – Declares a variable day with value 3.

  2. val result = day match { – Uses pattern matching to assign a value based on day.

  3. case 3 => "Wednesday" – When day is 3, assigns "Wednesday" to result.

  4. case _ => "Unknown" – The wildcard _ handles unmatched cases, assigning "Unknown".


Example 3: Lists and Iteration

val numbers = List(1, 2, 3, 4, 5)

for (num <- numbers) {
  println(s"Number: $num")
}

Explanation:

  1. val numbers = List(1, 2, 3, 4, 5) – Creates a list of numbers from 1 to 5.

  2. for (num <- numbers) { – Iterates over each element in numbers.

  3. println(s"Number: $num") – Prints "Number: X" where X is the list element.

  4. } – Ends the loop after processing all elements in numbers.


Example 4: Higher-Order Functions (map)

val numbers = List(1, 2, 3)
val doubled = numbers.map(x => x * 2)
println(doubled)

Explanation:

  1. val numbers = List(1, 2, 3) – Defines a list containing 1, 2, 3.

  2. val doubled = numbers.map(x => x * 2) – Applies a function that doubles each element.

  3. x => x * 2 – Anonymous function that multiplies each x by 2.

  4. println(doubled) – Prints List(2, 4, 6), the transformed list.


This is Lesson 2 of Scala programming covering conditions, pattern matching, loops, and higher-order functions.

More from this blog

Programming , Big Data, DevOps, etc

271 posts

Programming , Big Data, DevOps, etc