In any programming language, there are two types of functions:
- Pure Funtions
- Impure Functions
There is a basic difference between the two, that is pure function doesn’t change the variable it’s passed and an impure function does. For example, there exists a function which increases the input by 10. So, there are two possibilities, the first one is it could directly return x + 10 and so x does not change whereas in another case it could go with the statement like x = x + 10 and then return x, thus changing the value of x. So, the first function is pure whereas the other is impure.
Pure Function in scala
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something.
They are those functions which don’t read any other values except those given as input and follows its internal algorithm to produce the output. A pure function is side-effect free i.e it doesn’t change the value of the variable implicitly and thus doesn’t end up altering the values of the input.
These Scala String methods are also pure functions:
A pure function can be made as shown in the following program code:
Square of the number is 16 Number is 4
Now, we know that these function don’t change the variable implicitly so we add the result of two different functions in different ways, as shown:
Output in case 1 :36 Output in case 2 :36
Now, as output of both the cases are same then it is proved that input in the pure function in scala is not changed implicitly.
Below are befits Of using Pure Functions:
- They don’t cause any implicitly changes in input.
- They are easier to test.
- They can be debug easily.
- Scala | aggregate() Function
- Scala | reduce() Function
- Scala | Function Composition
- 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 Map
- Scala | Either
- Set in Scala | Set-2
- Set in Scala | Set-1
- Scala Keywords
- Scala Int >>>(x: Int) method with example
- Scala Map take() method with example
- Scala Int ^(x: Int) method with example
- Continuations in Scala
- Scala Map last() method with example
- Scala Int self() method with example
- How to get all the keys from a Scala map
- Scala Set &~() method with example
- Scala Set contains() method with example
- Scala Int | (x: Int) method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.