liveBook · Manning

Pure function

As explained in Kotlin in Action, 2E

A pure function is a function whose output is determined solely by its explicit inputs and whose evaluation has no externally observable side effects.

A pure function returns the same result for the same inputs, changes no other object’s state, and does not interact with the outside world. This makes behavior easier to reason about, reuse, and test. section 1.2.3

Pure functions support several practical advantages:

  • They reduce reliance on mutable variables, loops, and branching by enabling concise functional abstractions. section 1.2.3
  • They help avoid unsafe shared-data modification in concurrent programs when combined with immutable data structures. section 1.2.3
  • They can be tested in isolation without constructing the surrounding environment required by code that interacts with the outside world. section 1.2.3

A composed functional pipeline

A Kotlin collection pipeline can express successive operations as function values: messages are filtered, mapped to senders, deduplicated, and sorted. The example illustrates the concise composition associated with functional programming; purity still depends on the behavior of the functions involved. section 1.2.3

A lambda is not automatically pure

A lambda used as a button click handler can print "I was clicked!". Lambda syntax makes behavior concise, but the observable output means the handler is not side-effect-free. section 5.1.1

messages
   .filter { it.body.isNotBlank() && !it.isRead }
   .map(Message::sender)
   .distinct()
   .sortedBy(Sender::name)

Browse a compact Kotlin pipeline showing filtering, mapping, deduplication, and sorting as composable operations. section 1.2.3

How Kotlin in Action, 2E covers it

How deep it goes
Defines deterministic results and absence of side effects, then connects purity to concurrency, testing, and reasoning.
Examples
Shows a collection pipeline and contrasts concise lambda syntax with a button handler that produces observable output.
What you can do after
Evaluate/understand whether functions are repeatable, isolated, and free from observable interaction with surrounding state.
How it connects
Connects pure functions with immutability, first-class functions, lambda expressions, concurrency, and testing.

Also explained in

Compare how 19 books explain pure function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.