Scala Functions & Methods
Functions are the heart of Scala. You define methods with def, and you can also create function values that are stored in variables and passed around. This chapter covers methods; lambdas and function values follow in later chapters.
Defining a method
def greet(name: String): String =
s"Hello, $name!"
def add(a: Int, b: Int): Int = a + b
@main def run(): Unit =
println(greet("Lina"))
println(add(2, 3))Hello, Lina!
5
| Part | Meaning |
|---|---|
def |
starts a method definition |
greet |
the method name |
(name: String) |
parameters with required types |
: String |
the return type (optional for most methods, but recommended for public ones) |
= … |
the body; its last expression is the result |
There is no return keyword in normal Scala code: the value of the body is the return value.
Multi-line bodies
def bmi(weightKg: Double, heightM: Double): String =
val value = weightKg / (heightM * heightM)
val category =
if value < 18.5 then "underweight"
else if value < 25 then "normal"
else "overweight"
f"BMI $value%.1f ($category)"
@main def run(): Unit =
println(bmi(70, 1.75))
println(bmi(95, 1.80))BMI 22.9 (normal)
BMI 29.3 (overweight)
Methods that return Unit
Methods whose only job is a side effect — printing, writing a file — return Unit.
def banner(title: String): Unit =
val line = "=" * (title.length + 4)
println(line)
println(s"| $title |")
println(line)
@main def run(): Unit =
banner("Scala")=========
| Scala |
=========
Methods without parameters
A method can have an empty parameter list () or no list at all. The convention: use () when the method has a side effect, leave it out when it simply computes a value.
object Counter:
private var count = 0
def increment(): Unit = count += 1
def current: Int = count
@main def run(): Unit =
Counter.increment()
Counter.increment()
println(Counter.current)2
Nested methods and recursion
Methods can be defined inside other methods, which keeps helpers private to where they are used. A method that calls itself is recursive; recursive methods must declare their return type.
def factorial(n: Int): BigInt =
def loop(i: Int, acc: BigInt): BigInt =
if i <= 1 then acc else loop(i - 1, acc * i)
loop(n, 1)
@main def run(): Unit =
println(factorial(5))
println(factorial(25))120
15511210043330985984000000
Varargs
A parameter of type T* accepts any number of arguments, which arrive as a sequence.
def average(numbers: Double*): Double =
if numbers.isEmpty then 0.0 else numbers.sum / numbers.length
@main def run(): Unit =
println(average(1, 2, 3, 4))
println(average())
val scores = List(80.0, 90.0)
println(average(scores*))2.5
0.0
85.0
scores* spreads an existing collection into a varargs parameter.
Methods vs. functions
Method (def) |
Function value (val f = …) |
|
|---|---|---|
| Defined with | def name(params) = … |
(params) => … |
| Is an object? | no, belongs to a class/object/file | yes, an instance of Function1, Function2, … |
| Can be passed around | yes, Scala converts it automatically | yes |
| Can be generic / have defaults | yes | generics are possible but rarer; no defaults |
In practice the difference rarely matters: you can pass a method wherever a function is expected, e.g. List(1, 2).map(double).
Tip: Keep methods short and focused. A method that fits on a screen and does one thing is easy to test and easy to name.
Test yourself
What does a Scala method return if it has no return keyword?
- Nothing, it must use
return - The value of the last expression in its body
- Always
Unit null
Which part of a method definition is mandatory for each parameter?
- A default value
- Its type
- The
valkeyword - A comment
How do you pass an existing List[Int] named xs to def sum(ns: Int*)?
sum(xs)sum(xs*)sum(*xs)sum(xs.toArray)