Scala - Functions Example

1. Introduction

Functions in Scala can be defined, passed as parameters, returned from other functions, and stored in variables. They provide a way to encapsulate reusable logic and are foundational to Scala's functional programming style. In this blog post, we will explore how to define and use functions in Scala.

Scala - Functions

Scala functions are declared with the def keyword, followed by a name, parameter list, return type, and body. They can have zero or more parameters and can also be parameterless. Functions can be nested, meaning you can define functions within functions for modularity and encapsulation.

2. Program Steps

1. Define a simple function.

2. Demonstrate a function with parameters.

3. Show how to use default parameter values in functions.

4. Create and use a function with a variable number of arguments (varargs).

5. Execute the program to see functions in action.

3. Code Program

object FunctionDemo extends App {
  // Function without parameters
  def greet(): Unit = println("Hello, World!")

  // Function with parameters
  def add(x: Int, y: Int): Int = x + y

  // Function with default parameters
  def greetName(name: String = "Guest"): Unit = println(s"Hello, $name!")

  // Function with varargs
  def printNumbers(numbers: Int*): Unit = numbers.foreach(println)

  // Execute functions
  greet() // Calling function without parameters
  println(add(5, 3)) // Calling function with parameters
  greetName() // Calling function with default parameter
  greetName("Alice") // Calling function with specified parameter
  printNumbers(1, 2, 3, 4, 5) // Calling function with varargs
}

Output:

Hello, World!
8
Hello, Guest!
Hello, Alice!
1
2
3
4
5

Explanation:

1. greet is a parameterless function that simply prints a greeting message.

2. add is a function with two parameters x and y, and it returns their sum. The return type is inferred to be Int since the function body consists of an integer addition.

3. greetName demonstrates default parameters. If called without arguments, it uses "Guest" as the default value for name.

4. printNumbers uses a vararg parameter numbers to print each number in the list. The numbers argument is treated as a sequence within the function body, allowing iteration.

5. The program then executes each function, demonstrating its behavior and the printed output for each function call.


Comments