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

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs