What is functional programming?
Purity · Referential transparencyFunctional programming (FP) is programming with pure functions: functions whose only job is to compute a result from their inputs. No printing, no database writes, no mutating variables outside themselves — those are side effects.
The book opens with a coffee shop. An impure buyCoffee charges a credit card as a side effect, which makes it painful to test (you'd bill a real card!) and impossible to reuse (buying 10 coffees charges the card 10 times when you wanted one combined charge). The fix: return the charge as data instead of performing it.
// Impure: charging happens inside the function (invisible side effect) def buyCoffee(cc: CreditCard): Coffee = { val cup = new Coffee() cc.charge(cup.price) // side effect! cup } // Pure: return the charge as a value, let the caller decide what to do def buyCoffee(cc: CreditCard): (Coffee, Charge) = { val cup = new Coffee() (cup, Charge(cc, cup.price)) }
Buy three coffees in each shop, then look at what the "payment system" saw. Same clicks, very different consequences.