Open In App

Scala | Partially Applied functions

Last Updated : 11 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 exception. these arguments which are not passed to function we use underscore( _ ) as placeholder. Some important points:

  • Partially applied functions are helpful in minimizing a function which accepts many arguments to a function that accepts only some arguments.
  • It can replace any number of arguments defined by a function.
  • It is easier for users to utilize this method.

Syntax:

val multiply = (a: Int, b: Int, c: Int) => a * b * c

// less arguments passed
val f = multiply(1, 2, _: Int)

As we can see in above syntax we defined a normal function multiply which have three arguments we pass less arguments (two). we can see it does not throw an exception that is partially applied function. Example: 

Scala




// Scala program of Partially
// applied functions
 
// Creating object
object Applied
{
 
    // Main method
    def main(args: Array[String])
    {
 
        // Creating a Partially applied
        // function
        def Book(discount: Double, costprice: Double)
        : Double =
        {
 
            (1 - discount/100) * costprice
 
        }
 
        // Applying only one argument
        val discountedPrice = Book(25, _: Double)
 
        // Displays discounted price
        // of the book
        println(discountedPrice(400))
 
    }
}


Output:

300.0

Here, the discount is passed in the argument and costprice part is left empty which can be passed later when required so, the discounted price can be calculated any number of times. Some more examples of Partially applied functions:

  1. A partially applied function can be obtained even when not applied on any of the arguments defined. Example: 

Scala




// Scala program of Partially
// applied functions
 
// Creating object
object Applied
{
 
    // Main method
    def main(args: Array[String])
    {
 
        // Creating a Partially applied
        // function
        def Mul(x: Double, y: Double)
        : Double =
        {
            x * y
        }
 
        // Not applying any argument
        val r = Mul _
 
        // Displays Multiplication
        println(r(9, 8))
    }
}


Output:

72.0
  1. Partially applied functions can be utilized to replace any number of parameters. Example: 

Scala




// Scala program of Partially
// applied functions
 
// Creating object
object Applied
{
 
    // Main method
    def main(args: Array[String])
    {
 
        // Creating a Partially applied
        // function
        def Mul(x: Double, y: Double, z: Double)
        : Double =
        {
            x * y * z
        }
 
        // applying some arguments
        val r = Mul(7, 8, _ : Double)
 
        // Displays Multiplication
        println(r(10))
    }
}


Output:

560.0
  1. Currying approach can be utilized in Partially applied functions to transmit a function with multiple arguments into multiple functions, where each function takes only one argument. Example: 

Scala




// Scala program of Partially
// applied functions using
// Currying approach
 
// Creating object
object curr
{
 
    // Main method
    def main(args: Array[String])
    {
 
        // Creating a Partially applied
        // function
        def div(x: Double, y: Double)
        : Double =
        {
            x / y
        }
 
        // applying currying approach
        val m = (div _).curried
 
        // Displays division
        println(m(72)(9))
    }
}


Output:

8.0
  1. Here, currying approach breaks the given function into two functions, where each function takes one parameter so, you need to pass one value for each of the functions and get the desired output.


Similar Reads

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
Currying Functions in Scala with Examples
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 tw
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 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
How to Install Scala IDE For Eclipse?
In this tutorial, we'll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala. Requirement for InstallationEclipse (Install link) if you don't know how to install Eclipse then refer to this article.JDK 11 (you may use JDK 6 onwards) Note: If you do not have JDK installed, you may get them from this link. I
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
Scala Int <(x: Char) method with example
The <(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).<(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Scala Int <=(x: Double) method with example
The <=(x: Double) method is utilized to return true if the specified int value is less than or equal to the double value, otherwise returns false. Method Definition: (Int_Value).<=(Double_Value) Return Type: It returns true if the specified int value is less than or equal to the double value, otherwise returns false. Example #1: // Scala prog
1 min read
Scala Int <=(x: Byte) method with example
The <=(x: Byte) method is utilized to return true if the specified int value is less than or equal to the byte value, otherwise returns false. Method Definition: (Int_Value).<=(Byte_Value) Return Type: It returns true if the specified int value is less than or equal to the byte value, otherwise returns false. Example #1: // Scala program of I
1 min read
Parameterless Method in Scala
Prerequisites - Scala | Functions A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle. Exa
2 min read
Article Tags :