Search code examples
javafunctional-programmingpure-function

Pure functions can change input values?


I'm studying functional programming and I just read about Pure functions.

My question is: A pure function can change its parameters?

Is this function pure?

int a(Payment payment){
 payment.setValue(payment.getValue() - 1);
 return payment.getValue() * 10;
}

Solution

  • Two things here:

    1. A pure function is a function with return value based only on its input arguments, and calling the function has no side effects.

    2. The piece of Kotlin code you pasted doesn't compile (see https://ideone.com/fli05T). The compiler says val cannot be reassigned. It's because in Kotlin, function arguments are immutable.

    In theory, if it was possible to define such function as you wrote, then by definition from (1), it would be pure, assuming that the parameters are passed by value (changing them inside the function doesn't change them as seen from outside the function).