## Scala program examples

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-07-10 12:32:54 Viewed : 77

Scala program examples :

Here are a few Scala program examples that demonstrate various concepts:

1. Hello, World!: A simple Scala program that prints "Hello, World!" to the console.
```scalaobject HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}```
1. Factorial Calculation: A program that calculates the factorial of a given number using recursion.
```scalaobject Factorial {
def factorial(n: Int): Int = {
if (n <= 0) 1
else n * factorial(n - 1)
}

def main(args: Array[String]): Unit = {
val num = 5
val result = factorial(num)
println(s"The factorial of \$num is \$result")
}
}```
1. Fibonacci Series: A program that generates the Fibonacci series up to a given number of terms.
```scalaobject Fibonacci {
def fibonacci(n: Int): List[Int] = {
def fibHelper(n: Int, a: Int, b: Int, acc: List[Int]): List[Int] = {
if (n <= 0) acc
else fibHelper(n - 1, b, a + b, a + b :: acc)
}

fibHelper(n, 0, 1, List(0))
}

def main(args: Array[String]): Unit = {
val numTerms = 10
val series = fibonacci(numTerms)
println(s"The Fibonacci series up to \$numTerms terms: \$series")
}
}```
1. Case Class and Pattern Matching: A program that demonstrates the usage of case classes and pattern matching to represent and process geometric shapes.
```scalasealed abstract class Shape

case class Circle(radius: Double) extends Shape

case class Rectangle(width: Double, height: Double) extends Shape

case class Square(side: Double) extends Shape

object ShapeArea {
def calculateArea(shape: Shape): Double = shape match {
case Rectangle(width, height) => width * height
case Square(side) => side * side
}

def main(args: Array[String]): Unit = {
val circle = Circle(5.0)
val rectangle = Rectangle(4.0, 6.0)
val square = Square(3.0)

val circleArea = calculateArea(circle)
val rectangleArea = calculateArea(rectangle)
val squareArea = calculateArea(square)

println(s"Circle area: \$circleArea")
println(s"Rectangle area: \$rectangleArea")
println(s"Square area: \$squareArea")
}
}```

These are just a few examples to give you a taste of Scala programming. Scala offers a wide range of features, such as functional programming, immutability, pattern matching, and type inference, which can greatly enhance the expressiveness and conciseness of your code.