Pure functions

The definition of a pure function says that, if the return value of a function is completely dependent on its arguments/parameters, then this function may be referred to as a pure function. So, if we declare a function as fun func1(x:Int):Int, then its return value will be strictly dependent on its argument, x; say, if you call func1 with a value of 3 N times, then, for every call, its return value will be the same.

The definition also says that a pure function should not actively or passively cause side effects, that is, it should not directly cause side effects, nor should it call any other function that causes side effects.

A pure function can be either a lambda or a named function.

So, why are they called pure functions? The reason is quite simple. Programming functions originated from mathematical functions. Programming functions, over time, evolved to contain multiple tasks and perform anonymous actions that are not directly related to the processing of passed arguments. So, those functions that still resemble mathematical functions are called pure functions.

So, let's modify our previous program to make it into a pure function:

fun addNumbers(a:Int = 0,b:Int = 0):Int { 
    return a+b 
} 
 
fun main(args: Array<String>) { 
    println() 
} 

Quite easy, isn't it? We are skipping the output, as the program is really easy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.57.172