Scala: Partial functions andThen

Learn
1 min readJan 6, 2022

--

Partial functions can be chained to form a single function that encapsulates the effect of applying each of these functions one after the other on the argument provided.

The following example shows a few simple mathematical functions and how the combining of these into one function resulted in a function on whose execution the effect of all of the component functions get applied.

val seqOne: Seq[Int] = Seq(1,2,3,4,5,6)val oddThrice = new PartialFunction[Int, Int] {
def isDefinedAt(x : Int) = x % 2 == 1
def apply(x : Int) = x * 3
}
val oddSevenTimes = new PartialFunction[Int,Int] {
def isDefinedAt(x : Int) = x % 2 == 1
def apply(x : Int) = x * 7
}
val transformer = oddThrice.andThen(oddSevenTimes)
println(seqOne)
println(seqOne.map(transformer))
List(1, 2, 3, 4, 5, 6)
List(21, 42, 63, 84, 105, 126)

A caveat to note here is that the even numbers are also being multiplied even while isDefinedAt seems to indicate otherwise. This is because, the isDefinedAt needs to be explicitly utilized by the client code to effect the desired behavior of the multiplications happening only for odd numbers.

--

--

Learn
Learn

Written by Learn

On a continuing learning journey..

Responses (1)