Scala program to reverse a list

1. Introduction

Reversing a list is a common operation in programming. In Scala, there are multiple ways to reverse a list, but we'll be using the inbuilt reverse method provided by Scala's List collection. In this blog post, we will create a Scala program to reverse a given list.

2. Program Steps

1. Initialize the Scala environment.

2. Create a list.

3. Utilize the inbuilt reverse method to reverse the list.

4. Print the reversed list.

5. Execute the program.

3. Code Program

object ListReverser {
  def main(args: Array[String]): Unit = {
    // Create a sample list
    val originalList = List(1, 2, 3, 4, 5)

    // Reverse the list
    val reversedList = originalList.reverse

    println(s"Original List: $originalList")
    println(s"Reversed List: $reversedList")
  }
}

Output:

Original List: List(1, 2, 3, 4, 5)
Reversed List: List(5, 4, 3, 2, 1)

Explanation:

1. The program is encapsulated within the ListReverser object.

2. We define a sample list named originalList for demonstration purposes.

3. To reverse the list, we use the inbuilt reverse method which is available for lists in Scala. The result is stored in the reversedList variable.

4. Both the original and reversed lists are printed out in the main function.

5. As shown in the output, the original list List(1, 2, 3, 4, 5) gets reversed to List(5, 4, 3, 2, 1).


Comments