The apply() Function in Scala

Mohammad Irfan Feb 25, 2022
  1. Use apply() Function to Get the Sum in Scala
  2. Apply for Iterating List Elements in Scala
The apply() Function in Scala

Scala treats functions as objects and provides a built-in function apply() that executes after calling an object and can work for all the logic we write in a class. In Scala, the apply method follows some rules.

  1. Any object with an apply method can be called with the .apply omitted.
  2. Functions are no more than objects.

This tutorial will discuss the apply() function and implement it in Scala.

Use apply() Function to Get the Sum in Scala

The simplest use of the apply() function is by implementing it in a class and calling it a regular function. Here, we provided code to get the sum of two values and the result by calling the apply() function.

Syntax:

def apply(n: Int): A

The syntax returns an element from the given list by its index, present in the apply method as an argument.

Example:

class MyClass{
    def apply(a:Int, b:Int) = {
        a+b
    }
}
object MainObject{
    def main(args:Array[String]){
        var e = new MyClass()
        val result = e.apply(10,80)
        println(result)

    }
}

Output:

90

Apply for Iterating List Elements in Scala

This is another use case of the apply() function. We are traversing the list element by calling it.

Example:

class MyClass{
    def apply(list:List[Integer]) = {
         for( i <- list){
            println(i)
        }
    }
}
object MainObject{
    def main(args:Array[String]){
        var e = new MyClass()
        e.apply(List(0,8,12))
    }
}

Output:

0
8
12

We can also use the apply() function to call a lambda expression written in the composite function. Lambda expression is an expression that uses an anonymous function instead of a variable or value.

Example:

object MainObject{
    def main(args:Array[String]){
        val f = (x:Int) => x * 10
        val e = f.compose((x:Int) => x - 2)
        val result = e.apply(12)
        print(result)
    }
}

Output:

100

The common use of the apply() function is to get an element by its index value. It means we can get elements of any container by calling it.

Example:

object MainObject{
    def main(args:Array[String]){
        val list = List(5, 7, 5, 2)
        // Applying the apply function
        val result = list.apply(2)
        print(result)
    }
}

Output:

5