Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-07-10 07:02:54 Viewed : 638
Scala program examples :
Here are a few Scala program examples that demonstrate various concepts:
scalaobject HelloWorld { def main(args: Array[String]): Unit = { println("Hello, World!") } }
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") } }
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") } }
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 Circle(radius) => math.Pi * radius * radius 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.