×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Partial functions in Scala

By IncludeHelp Last updated : October 20, 2024

Scala partial functions

A partial function is a function that returns values only for a specific set of values i.e. this function is not able to return values for some input values. This function is defined so that only some values are allowed in the processing of the code. Like in the case of division by 0, we need to restrict the division to avoid errors.

These are inconsistent functions of Scala programming language and in some cases, they can be of great use.

Implementation of partial functions

The implementation of partial functions in Scala needs other methods too. The methods that are used for implementation are apply() and isDefinedAt(). Also, you use the case statements to implement it.

The apply() method is used to show the application of a function.

The isDefinedAt() method is used to check if the values are in the range of function or not.

Syntax

var function_name = new PartialFunction[input_type, return_type]

Example 1

Implementing partial function using isdefinedat() and apply() methods.

object MyObject 
{ 
    val divide = new PartialFunction[Int, Int] 
    { 
        def isDefinedAt(q: Int) = q != 0
        def apply(q: Int) = 124 / q 
    } 

    def main(args: Array[String]) 
    { 
        println("The number divided by 12 is " + divide(12))
    } 
} 

Output

The number divided by 12 is 10

Example 2

Implementation of partial function using orElse statement.

object MyObject
{ 
    val Case1: PartialFunction[Int, String] =
    { 
        case x if (x % 3) != 0 => "Odd"
    } 
    val Case2: PartialFunction[Int, String] =
    { 
        case y if (y % 2) == 0 => "Even"
    } 
    val evenorodd = Case1 orElse Case2
    
    def main(args: Array[String]) 
    { 
        var x= 324
        println("The number "+x+" is "+evenorodd(x))
    } 
} 

Output

The number 324 is Even

Example 3

Implementation of partial function using andThen statement.

object MyObject
{ 
    def main(args: Array[String]) 
    { 
        val operation1: PartialFunction[Int, Int] =
        { 
            case x if (x%4)!= 0=> x*42
        } 
        
        val operation2=(x: Int)=> x/3
        val op = operation1 andThen operation2 
        println("Initial value is 34\t and the value after operations is "+op(34)) 
    } 
} 

Output

Initial value is 34	 and the value after operations is 476

Comments and Discussions!

Load comments ↻





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