In Kotlin you can write pure functions and harness the power of functional programming in a similar fashion to Scala.
Side-Effects are state changes that persist out side of the local return value of a function. Mutator methods of a class are an example of functions that create side-effects, these kinds of functions are called procedures.
Referential Transparency is the idea in functional programming where replacing a function call with it's returned result will not change how the program behaves.
Pure Functions are referentially transparent because they do not create any side-effects.
The benefit of referential transparency in pure functions show up quiet apparently: The program becomes no less complex to reason about than an algebraic expression.
Here is an example of a pure function:
fun abs(n: Int): Int = Math.abs(n)
Here is an example of an impure function:
class Burger(var eaten: Boolean) {
fun eat() {
this.eaten = true // changing the state is an example of a side-effect
}
}
Top comments (0)