Functions
9 min · Scala
Package code under a name so you can reuse it.
Enemy 1 of 5
Defining a function with def
Once a calculation is useful in more than one place — doubling a number, formatting a name, checking whether a value is valid — copying and pasting it everywhere becomes a liability: if the logic ever needs to change, you'd have to find and fix every copy. A function packages a piece of logic under a name once, so every place that needs it can just call that name instead of repeating the logic.
`def double(n: Int): Int = n * 2` breaks down into four parts: `def` starts the definition, `double` is the name you'll call it by, `(n: Int)` declares a parameter named `n` with type `Int` (Scala requires parameter types to be written explicitly — they're not inferred, unlike `val`), and `: Int` after the closing parenthesis declares the return type. Everything after the `=` is the function's body — for a one-line function like this, no curly braces are needed, and the value of that single expression is automatically returned.
For longer bodies you'll use curly braces (`def double(n: Int): Int = { ... }`), and the value of the *last* expression inside the braces becomes the return value — there's no separate `return` keyword needed in idiomatic Scala (it exists but is rarely used). This "last expression wins" rule is different from languages like Java or Python where you must write an explicit `return`, and it takes a little getting used to.
Loading editor...