Back2Basics: Partial functions and Partially applied functions in Scala

Reading Time: 2 minutes

Hi Folks, in this blog I will discuss about the difference between Partial Functions and Partially Applied Functions in Scala, importance of these functions and how we can use them in our code.

Before discussing about Partial Function and Partially Applied Functions, we should know about Functions.

What is Function?

A Function is a transformation for an input into an output which means whenever an input is provided it will generate an output.

scala> def isEven(x :Int) = x % 2 == 0
isEven: (x: Int)Boolean

scala> def isOdd(x :Int) = x % 2 != 0
isEven: (x: Int)Boolean

scala> isEven(12)
res0: Boolean = true

scala> isOdd(11)
res1: Boolean = false

Now, we know what Function is, how it works, so lets move to the next part.

Partial Functions

Functions that are not able to satisfy every condition or does not work for every input, such type of methods are know as Partial functions.

Partial Functions, a unary function that does not support every possible value that meets the input type. These are defined only for certain domain of input values.

val squareRoot: PartialFunction[Double, Double] = {
  case x if x >= 0 => Math.sqrt(x)
}

Partial functions can be chained together using orElse or andThen.

val positive: PartialFunction[Int, Int] = {
case x if x >= 0 => x
}

val odd: PartialFunction[Int, Boolean] = {
case x if x % 2 == 1 => true
}

val even: PartialFunction[Int, Boolean] = {
case x if x % 2 == 0 => true
}

val evenCheck: PartialFunction[Int, Boolean] = positive andThen even

val oddCheck: PartialFunction[Int, Boolean] = positive andThen odd

Partially Applied Functions

Whenever we call a function with all of the required parameters, it is a fully applied function but there might be a situation when all the parameters are not present at a certain point of time so we can skip that parameter by _ and can pass that parameter when ever it is available so such type of methods are knows as Partially Applied Functions in Scala.

scala> def sum (a: Int, b: Int, c: Int) = a + b + c
sum: (Int, Int, Int) Int

scala> val halfValue = sum (1, _: Int, 3)
b: (Int) => Int = <function>

scala> halfValue(2)
res0: Int = 6

Hope this blog will help you.

Happy Blogging!

References:-


Knoldus-blog-footer-image

Written by 

Sanjana Aggarwal is a Software Consultant at Knoldus Software LLP, having experience of more than 1.5 years. She has done MCA from Bharati Vidyapeeth Institute of Computer Application and Management, Paschim Vihar. She has a decent knowledge of Java, Scala, Lagom, Kafka, Cassandra, Cocuhbase, MongoDB, Akka and Akka HTTP. She loves reading books and cooking and traveling.

Leave a Reply