Functions
9 min · Scala
Package code under a name so you can reuse it.
Enemy 1 of 5
Defining a function with def
A function gives a piece of logic a name. Write it once, then call that name anywhere you need it. If the logic changes, you fix it in one place.
This defines a function named double that takes an Int and returns it times 2. The last expression is the result, so no return is needed. Press Run to see it.
Why this works
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.