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.