Scala Functions

Learn via video courses
Topics Covered

Overview

A function in Scala is a group of statements that collectively perform a specific task. In Scala, functions can be assigned to variables, passed as arguments to other functions, and returned as results from other functions. Scala functions are considered first-class citizens, meaning they have the same rights and capabilities as any other value or object in the language. It allows you to organize your code into smaller, modular units. The division of code into functions is flexible and can be determined based on logical considerations.

Introduction

Scala functions are one of the fundamental strengths of its functional programming paradigms. A function in Scala is a named, reusable block of code that can take parameters, perform computations, and optionally return a value. Functions can be assigned to variables, passed as arguments, and returned from other functions. This versatility in parameterization and return type allows functions to handle diverse scenarios and provide desired outcomes.

In Scala, the terms function and method are used interchangeably with a slight distinction. A method in Scala is associated with a class and has a name, signature, optional annotations, and bytecode. On the other hand, a function in Scala is a self-contained object that can be assigned to a variable. Essentially, a function defined within an object is referred to as a method.

Function Declarations

A function declaration is a prototype that specifies the function name, return types, and parameters without the function body. In Scala, function declaration consists of the def keyword followed by the function name, a list of parameters enclosed in parentheses, and an optional return type declaration.

Here's the general syntax for function declaration in Scala:

Function Definitions

In Scala, function definition refers to the process of providing the implementation for a declared function. A function definition is the combination of function declaration along with its implementation or body, enclosed in curly braces.

Here's an example of a function definition in Scala:

In the above function definition, we have a function named greet that takes a single parameter name of type String. The : Unit part denotes that the function does not return a value (similar to void in other languages). The function body, enclosed in curly braces {}, contains the code that executes when the function is called. In this case, it prints a greeting message using string interpolation.

Syntax

Scala functions are defined using the def keyword followed by the function name, a list of parameters enclosed in parentheses, an optional return type declaration, and a function body enclosed in curly braces. Here's the general syntax for defining a function in Scala:

Basic Scala Constructs

Constructs in Scala refer to the fundamental building blocks and language features that enable us to write code and define program structures. These constructs provide the foundation for expressing logic, data manipulation, control flow, and organization within Scala programs.

Here are some of the basic constructs in Scala:

  1. Scala Expression:
    An expression in Scala is a combination of values, variables, operators, and function calls that evaluates to a single value.
  2. Scala Block:
    A block in Scala is a sequence of expressions enclosed in curly braces {}. It groups multiple expressions and can be used to define local variables and perform multiple operations.
  3. Scala Class:
    In Scala, a class is a blueprint for creating objects. It defines the properties (fields) and behavior (methods) that objects of the class will have.
  4. Scala Object:
    An object in Scala is a single instance of a class. It is similar to a static class in other languages.
  5. Scala Function:
    A function in Scala is a named, reusable block of code that can take parameters, perform computations, and optionally return a value.
  6. Scala Method:
    A method in Scala is a member of a class or object that defines behavior specific to that class or object.
  7. Scala Trait:
    A trait in Scala is similar to an interface in other languages. It defines a set of abstract methods and fields that can be mixed into classes or other traits to provide reusable behavior.
  8. Scala Main Method:
    The main method is the entry point for a Scala program. A Scala program must have a main method defined in an object to run.
  9. Fields:
    Fields in Scala are variables or values declared within a class or object.
  10. Closure:
    Closures are Scala functions that bind the variables together with the function code, creating a self-contained unit that can be passed around and executed independently.

Calling Functions

Once a function is defined, it can be invoked by the function name and arguments that match the declared parameter types.

For example:

In this case, the add function is called with arguments 3 and 4, and the returned sum is assigned to the result variable.

Here is another example:

Here, the greet function is called with a string argument Virat, and prints the message of "Hey, Virat!" without returning anything as its return type is Unit.

function example in scala

Example

Let's understand the functions in scala in more depth with the help of the following example:

Output:

Explanation:

In this example, we have defined two functions: sum and isEven. The sum function takes two integer parameters a and b and returns their sum. The isEven function takes an integer parameter number and checks if it is even, returning a Boolean value indicating the result.

In the main function, we demonstrate the use of these functions by calling them and printing the results. We invoke the sum function with arguments 5 and 3 and store the returned sum in the result variable. We then print the sum using string interpolation. Next, we use the isEven function to check if the number 10 is even or odd and display the corresponding message based on the returned result.

Output

The output of Scala functions can be classified into two main categories:

Functions with Return Values

These are the functions that are designed to produce a result or value. The return type of such functions can be explicitly declared or inferred by the Scala compiler. The output of these functions can be captured and utilized in different ways, such as assigning it to a variable, passing it as an argument to another function, or using it directly in expressions.

Example:

Explanation:

In this example, the add function takes two Int parameters and returns their sum as an Int. The result of the function call add(2, 5) is captured in the result variable. The output of the function, which is the sum of 2 and 5, is then printed as Sum: 7.

Functions without Return Values

These are the functions that don't explicitly return a value or have a return type of Unit. These functions are typically used for performing actions or side effects, such as printing to the console, modifying mutable state, or invoking other functions.

Example:

Explanation:

In this example, the greet function takes a String parameter and prints a greeting message to the console. The output of the function is the printed message "Hey, Virat!". Since the return type is Unit, no value is explicitly returned or captured.

Conclusion

  • Scala functions are self-contained blocks of code that can be defined and invoked to perform specific tasks.
  • Functions are considered first-class citizens in Scala, which means they can be treated as values, assigned to variables, and passed as arguments to other functions.
  • Functions in Scala are declared using the def keyword followed by the function name, a list of parameters, an optional return type declaration, and a function body enclosed in curly braces.
  • The defined Scala functions can be invoked in the program by the function name and parameters enclosed in ( ).
  • Constructs in Scala refer to the fundamental building blocks or syntactic elements of the language, such as variables, functions, classes, conditional statements, loops, and more, used to structure and express code.
  • Functions in Scala can return a value or no value (Unit). The return type is declared in the function declaration after the parameter list.
  • They enable us to encapsulate behavior, promote code reuse, and leverage the benefits of functional programming paradigms.