Open In App

Currying Functions in Scala with Examples

Last Updated : 13 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument. It is applied widely in multiple functional languages.
 
Syntax

def function name(argument1, argument2) = operation

Let’s understand with a simple example,
Example:




// Scala program add two numbers
// using currying Function
object Curry
{
    // Define currying function
    def add(x: Int, y: Int) = x + y;
  
    def main(args: Array[String])
    {
        println(add(20, 19));
    }
}


Output:

39

Here, we have define add function which takes two arguments (x and y) and the function simply adds x and y and gives us the result, calling it in the main function.

Another way to declare currying function
Suppose, we have to transform this add function into a Curried function, that is transforming the function that takes two(multiple) arguments into a function that takes one(single) argument.
 
Syntax

def function name(argument1) = (argument2) => operation

Example




// Scala program add two numbers
// using Currying function
  
object Curry
{
    // transforming the function that 
    // takes two(multiple) arguments into 
    // a function that takes one(single) argument.
    def add2(a: Int) = (b: Int) => a + b;
  
    // Main method
    def main(args: Array[String])
    {
        println(add2(20)(19));
    }
}


Output:

39

Here, we have define add2 function which takes only one argument a and we are going to return a second function which will have the value of add2. The second function will also take an argument let say b and this function when called in main, takes two parenthesis(add2()()), where the first parenthesis is of the function add2 and second parenthesis is of the second function. It will return the addition of two numbers, that is a+b. Therefore, we have curried the add function, which means we have transformed the function that takes two arguments into a function that takes one argument and the function itself returns the result.

Currying Function Using Partial Application

We have another way to use this Curried function and that is Partially Applied function. So, let’s take a simple example and understand. we have defined a variable sum in the main function

Example




// Scala program add two numbers
// using Currying function
object Curry
{
    def add2(a: Int) = (b: Int) => a + b;
  
    // Main function
    def main(args: Array[String])
    {
        // Partially Applied function.
        val sum = add2(29);
        println(sum(5));
    }
}


Output:

34

Here, only one argument is passed while assigning the function to the value. The second argument is passed with the value and these arguments are added and result is printed.

Also, another way(syntax) to write the currying function.
 
Syntax

def function name(argument1) (argument2) = operation

Example




// Scala program add two numbers
// using Currying function
object Curry
{
    // Curring function declaration
    def add2(a: Int) (b: Int) = a + b;
  
    def main(args: Array[String])
    {
        println(add2(29)(5));
    }
}


Output:

34

For this syntax, the Partial Application function also changes.
Example




// Scala program add two numbers
// using Currying function
object Curry
{
    // Curring function declaration
    def add2(a: Int) (b: Int) = a + b;
  
    def main(args: Array[String])
    {
       // Partially Applied function.
        val sum=add2(29)_;
        println(sum(5));
    }
}


Output:

34

Here, only the ‘_’ is added after the calling the function add2 for value of sum.



Similar Reads

Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Using anonymous functions with the map method in Scala
In Scala, you can use anonymous functions with map method. And here we will discuss the usage of multiple line anonymous functions with map. Therefore, whenever you see that your algorithm is becoming lengthy then instead of utilizing an anonymous function you can firstly define the method and then you can pass it into the map or use it with the ma
2 min read
Scala | Functions - Basics
A function is a collection of statements that perform a certain task. One can divide up the code into separate functions, keeping in mind that each function must perform a specific task. Functions are used to put some common and repeated task into a single function, so instead of writing the same code again and again for different inputs, we can si
3 min read
Scala | Nested Functions
A function definition inside an another function is known as Nested Function. It is not supported by C++, Java, etc. In other languages, we can call a function inside a function, but it’s not a nested function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions. Synt
2 min read
Partial Functions in Scala
Introduction: When a function is not able to produce a return for every single variable input data given to it then that function is termed as Partial function. It can determine an output for a subset of some practicable inputs only. It can only be applied partially to the stated inputs. Some important points: Partial functions are beneficent in un
4 min read
Higher Order Functions in Scala
A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another functions are known as Higher order Functions. It is worth knowing that this higher order function is applicable for functions and methods as well that takes functions as parameter
3 min read
Anonymous Functions in Scala
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function. Syntax: (z:Int, y:Int)=> z*yOr(_:Int)*(_:Int)In the above first syntax, => is
2 min read
Scala Int Compare Method With Examples
compare is an int class method in Scala which is used to compare this with that operand. Syntax: (Given_Value1).compare(Given_Value2) Returns: return -1 when Given_Value1 is less than Given_Value2. return 0 when both values are equal. return 1 when Given_Value1 is greater than Given_Value2. Example 1: // Scala Program to demonstrate the // compare
1 min read
Scala Int CompareTo Method With Examples
compareTo is an int class method in Scala which is used to compare this with that operand. It is similar to the compare Method. Syntax: (Given_Value1).compareTo(Given_Value2)Returns: return -1 when Given_Value1 is less than Given_Value2. return 0 when both values are equal. return 1 when Given_Value1 is greater than Given_Value2. Example 1: C/C++ C
1 min read
Scala Double +(x: String) Method With Examples
The +(x: String) method is used to find the sum of the specified double and the given ‘x’ type of string in the argument. Syntax: def +(x: String): Double Returns: It return the sum of the specified double and the given string type ’x’. Example 1: // Scala program of +(x: String) // method // Creating object object GfG { // Main method def main(arg
1 min read
Scala Listset apply() method with examples
In Scala ListSet, apply() method is utilized to check if the given element is present or not in the listSet. Method Definition: final def apply(elem: A): Boolean Return Type: True if element is present else false. Example 1: // Scala program of apply() // method import scala.collection.immutable._ // Creating object object GfG { // Main method def
1 min read
Scala - String Methods with Examples
In Scala, as in Java, a string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In the rest of this section, we discuss the important methods of java.lang.String class. char charAt(int index): This method is used to returns the character at the given index. Example: C/
12 min read
Scala short <(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short <(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &() method with example
The &() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert
2 min read
Article Tags :