×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Partially Applied Functions in Scala

By IncludeHelp Last updated : October 20, 2024

Partially applied functions

Partially applied functions, are actually those function that allows you to implement function calls with partial arguments i.e. using only a few values in a function call and uses rest values form a common call initiation.

It's a bit trick concept, so to understand it lets take an example. Suppose you define need to find the percentage of all students. You define a general function that takes two arguments total marks and marks obtained and find the percentage. And for a class, the total marks are the same. The classical way is to pass to full arguments to each call of the function. But using the partially applied function, you can place one argument as a pre-defined argument that will use its values as arguments in the function call. As in our example, initialization of percentage method named ninth is made with an initial value of total marks argument defining it as a partially applied function.

Syntax

val pAfName = funcName(arg1Val, _ : datatype);
pAfName(arg2Val)

This syntax is for the initializing pAfName variable for function funcName that defines partial argument feed of arg1Val. This value can be used for later is code when the only arg2Val is used to call the function.

Example of Partially Applied Function

object myClass {
    def percentage(totalMarks: Int, marksObtained: Int) = {
      println("Percentage Obtianed :");
      println( ((marksObtained*100)/totalMarks) + " %")
   }
   
   def main(args: Array[String]) {
      val  ninth = percentage(350 , _ : Int)
      println("Student 1")
      ninth( 245 )
      println("Student 2")
      ninth( 325 )
      println("Student 3")
      ninth( 102 )
   }   
}

Output

Student 1
Percentage Obtianed :
70 %
Student 2
Percentage Obtianed :
92 %
Student 3
Percentage Obtianed :
29 %

Code explanation

The above code is based on the example that we have discussed in this tutorial. We have made a function percentage that prints the percent of the student. This function takes two arguments totalMarks and marksObtained. But for a set of function, the totalMarks will be the same. In this case, we have defined a function named ninth that has value 350. And this ninth function is used three times with different arguments that print the calculated result.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.