The 30 second answer
In classic Java you create an object and keep changing it: set this field, add to that list. In Scala you treat data as values that never change. A function takes a value and returns a new one, with no side effects, and a program is a pipeline of those functions. You stop asking who else might be modifying this object, because nobody can.
From "change this object" to "compute the next value". Imperative Java code usually works like a whiteboard: one object that many lines of code, and sometimes many threads, write on. Functional Scala code works like a production line: each step receives a value and hands a new value to the next step. The old value is still there, unchanged.
Pure functions. The Scala 3 book describes a pure function as one whose output depends only on its inputs and that has no side effects, such as mutating its arguments or writing to a database. Pure functions are easy to test (same input, same output), easy to reuse, and safe to run on any thread.
Pipelines. Instead of a loop that fills a mutable list, you describe the steps:
val topSkus = clicks
.filter(_.country == "DE") // keep German clicks
.groupMapReduce(_.sku)(_ => 1)(_ + _) // count per SKU, into a new Map
.toList
.sortBy(-_._2) // most clicked first
.take(10)Each line returns a new collection. Java streams express the same idea, but in Scala this is the everyday default rather than a special API.
Side effects at the edges. Real programs still read files, call Elasticsearch and write logs. The habit is to keep those effects at the edges (load, then a pure core, then write) so the core logic can be reasoned about and tested on its own.
Sources (2)
- Scala 3 book: Pure functionsdocs.scala-lang.org
- Scala collections overview: immutable collections are the defaultdocs.scala-lang.org