Scala Currying and Automatic Type-Dependent Closure Construction With Examples

Scala Currying is the process of transforming a function that takes multiple arguments into a single argument.

Consider an example of multiplying two numbers .Open the scala REPL shell and create the multiply method as

The multiply function accepts two arguments a and b of Integer data type and return the result of a*b which is of Integer data type.

Invoke the method as multiply(4,5) and you will get output as res10:Int = 20

Now let us apply the currying for this function as;

Output: multiply: (a: Int)Int => Int

The multiply function takes a single argument a of Integer data type in the function declaration. Inside the function it takes one more parameter b of Integer data type and return a* b as the result.

Suppose if we invoke the function with single argument the function closure reference is returned as

Invoke the function by passing two arguments as


Automatic Type Dependent Closure Construction

In scala, parameterless function names allows as parameters of methods. When such methods are called the nullary functions are evaluated and not the actual parameters for the parameterless function names. The nullary function encapsulates computation of the corresponding parameter called call-by-name evaluation.

Let’s look at an example to understand this more clearly.


We are creating an object TypeDependent which defines a method “forloop”. This method takes two parameters rule and body. Whenever the formal parameters are used in the body of forloop, the implicitly created nullary functions will be evaluated. Here we are implementing for loop, below image shows the output of above program.


Now let us have a look at more complex example with more operations.


We are creating a scala object which contains a method t1 that accepts body parameter of Unit data type and returns an instance of class Criteria. The criteria class defines has a method “condition” which checks the condition if x == 2 after decrementing the value of x. Below image shows the output of the above program.


Personally I don’t like this feature a lot because of complexity, but it’s good to know.

By admin

Leave a Reply

%d bloggers like this: