How to convert function to partial function in Scala?

Here, we will learn about the function, partial function and how to convert function to partial function in Scala?
Submitted by Shivang Yadav, on June 16, 2020

First, let's see what is a function and a partial function, and then we will see their conversion process.

Function in Scala is a block of code that is used to perform a specific task. Using a function you can name this block of code and reuse it when you need it.

Example:

def divide100(a : Int) : Int = {
	return 100/a;
}

Partial function in Scala are functions that return values only for a specific set of values i.e. this function is not able to return values for some input values.

Example:

def divide100 = new PartialFunction[Int , Int] {
	def isDefinedAt(a : Int) = a!=0
	def apply(a: Int) = 100/a
}

Convert function to partial function

You can replace a function with a partial function as the definition of the function cannot be changed by we will call the given function using our partial function which will convert the function to function.

Scala Program to convert function to partial function

//Convert function to partial function 
object MyClass {
    def divide100(x:Int) = 100/x;
    
    def dividePar = new PartialFunction[Int , Int] {
        def isDefinedAt(a : Int) = a!=0
        def apply(a: Int) = divide100(a)
    }
    
    def main(args: Array[String]) {
        print("100 divided by the number is " + dividePar(20));
    }
}

Output:

100 divided by the number is 5





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.