Open In App

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:

Example:




// Scala program of 
// Partial function
  
// Creating object 
object Case
{
  
    // Main method
    def main(args: Array[String])
    {
  
        // Creating Partial function 
        // using two methods
        val r = new PartialFunction[Int, Int] 
        {
  
            // Applying isDefinedAt method 
            def isDefinedAt(q: Int) = q != 0
  
            // Applying apply method
            def apply(q: Int) = 12 * q
  
        
  
        // Displays output if the
        // condition is satisfied
        println(r(10))
    }
}

Output:

120

Here, two methods are defined for applying Partial function, where isDefinedAt states the condition and apply performs the operation if the given condition is satisfied.
Methods to define Partial functions:
There are some methods to define Partial function, which includes case statements, collect method, andThen, and orElse.


Article Tags :