Function composition is a way in which a function is mixed with other functions. During the composition the one function holds the reference to another function in order to fulfill it’s mission.
There are some different ways in which a function composition can take place, as below :-
- compose : Composing method works with val functions.
(function1 compose function2)(parameter)
In the above syntax function2 works first with the parameter passed & then passes then returns a value to be passed to function1.
In above example, firstly mul function called we got 4(2 * 2) than add function called and we got 5(4 + 1). similarly (add compose mul compose sub)(2) will print 3 (step1 : 2 – 1 = 1, step2 : 1 * 2 = 2, step3 : 2 + 1 = 3).
(function1 andThen function2)(parameter)
In the above syntax function1 works first with the parameter passed & then passes then returns a value to be passed to function2.
or as same as below:
In above example, firstly add function called we got 3(2 + 1) than mul function called and we got 6(3 * 2). similarly add (andThen mul andThen sub)(2)) will print 5 (step1 : 2 + 1 = 3, step2 : 3 * 2 = 6, step3 : 6 – 1 = 5).
Function composition is more like composing methods into another or passing to other methods. To do more control on methods we can use more ways as below:-
- Passing methods to methods : Methods are passed to other methods.
It works as same as compose function, but it works with def and val methods.
In above example, firstly mul function called we got 4(2 * 2) than add function called and we got 5(4 + 1). similarly add(mul(sub(2)) will print 3 (step1 : 2 – 1 = 1, step2 : 1 * 2 = 2, step3 : 2 + 1 = 3).
- Inverse functions and composition of functions
- Scala | reduce() Function
- Pure Function In Scala
- Scala | aggregate() Function
- Program to transform an array of String to an array of Int using map function in Scala
- Scala Tutorial – Learn Scala with Step By Step Guide
- Scala | Either
- Set in Scala | Set-1
- Set in Scala | Set-2
- Scala Map
- Stack in Scala
- Scala | StringContext
- Scala Varargs
- Scala Int ==(x: Int) method with example
- Remove key value from Map in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.