DEV Community

Carter
Carter

Posted on

Functional Programming in Kotlin pt. 1

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)
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More