Scala Functions
A function is a named block of code that performs one job. You write it once and run it again by name whenever you need that job done.
The same calculation written twice
Without a function, the same calculation is typed out again for every new set of values. The price per item is repeated in both lines here.
@main def main(): Unit =
val apples = 3 * 50
println(apples)
val oranges = 5 * 50
println(oranges)One def replaces the copies
The def below holds the calculation once, in a function named cost. Its parameters are count and price, and its result type is Int.
def cost(count: Int, price: Int): Int = count * price
@main def main(): Unit =
println(cost(3, 50))
println(cost(5, 50))New values on every call
Each call runs the same function with fresh values. The results change because the input changes, not because the function changes.
def double(n: Int): Int = n * 2
@main def main(): Unit =
println(double(4))
println(double(9))
println(double(25))Example
def totalCost(count: Int, priceEach: Int): Int = count * priceEach
@main def main(): Unit =
val notebooks = totalCost(3, 120)
val pens = totalCost(6, 25)
println(notebooks)
println(pens)
println(notebooks + pens)Key points
- def: The keyword def starts a function definition.
- Parameter: A parameter is a named input slot that a function expects when it runs.
- Parameter type: The type written after a parameter name states what kind of value that slot accepts.
- Result type: The type written after the parameters states what kind of value the function gives back.
- Call: Writing the function name with values in parentheses runs the function.
- Reuse: One function can be called many times with different values.
In this example, the def totalCost multiplies a count by a price and gives back an Int. The first call works out 3 times 120, which is 360, and stores it in notebooks. The second call works out 6 times 25, which is 150, and the last line prints the two results added together.
Note
In Scala 3, a short function body can follow an equals sign on the same line.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does the line def add(a: Int, b: Int): Int = a + b do?