In Kotlin, a pure function is a function that always returns the same output for the same input parameters and does not modify any external state or variables. They only use the input parameters passed to them to generate a result.
Pure functions have several advantages over non-pure functions:
They are easier to reason about, test, and debug.
They are less error-prone because they do not depend on external state.
They are more efficient since they can be memoized (i.e., caching the result of a function call for a specific input).
The main difference between pure and simple functions is that pure functions always return the same output for the same given input, while simple functions might return different outputs for the same input, such as modifying a global variable or reading/writing to a file/database. These functions are not pure and can have unpredictable behavior.
The syntax for defining a pure function in Kotlin is the same as a simple function.
fun functionName(parameter1: Type1, parameter2: Type2): ReturnType {// Function body// ...return result}
Let’s take an example to understand the behavior of pure functions.
// Pure functionfun sum(a: Int, b: Int): Int {return a + b}// Simple functionvar sum = 0fun addToSum(num: Int) {sum += num}fun main() {val result = sum(3, 5)println(result) // Output: 8addToSum(2)addToSum(3)println(sum) // Output: 5}
Let’s discuss the above code in detail.
Lines 2–4: Define a pure function named sum
that takes two integer parameters, a
and b
, adds them together, and returns the result.
Line 7: Declare a global variable named sum
.
Lines 8–10: Define a simple function named addToSum
that takes an integer parameter num
and adds it to a variable named sum
. Note that the sum
is defined outside of the function and, therefore, can be modified by the function, making it impure.
Line 11: Define a main
function that calls both sum
and addToSum
functions and prints the results to the console.
Lines 12–13: Call the sum
function with the values 3
and 5
and assigns the result to a variable named result
. Then, print the value of the result
to the console.
Lines 15–17: Call the addToSum
function twice with values 2
and 3
, respectively, which modifies the value of the sum
variable to be 2 + 3 = 5
. Finally, print the value of sum
to the console, which is 5
.
Free Resources