Scala Return Values
A return value is the result that a function gives back to the code that called it. The caller can print that result or store it for later.
The last expression is the result
The body of add first works out the sum and stores it in a val. The name sum on the last line is the value the function gives back.
def add(a: Int, b: Int): Int =
val sum = a + b
sum
@main def main(): Unit =
println(add(4, 5))
println(add(10, 20))A def that only prints returns Unit
greet prints a message and gives back no value. Its result type is Unit, which marks a function run only for its action.
def greet(name: String): Unit =
println("Hello, " + name)
@main def main(): Unit =
greet("Ana")
greet("Ben")An if expression as the body
The whole body of verdict is one if expression. The condition picks which String becomes the result.
def verdict(score: Int): String =
if score >= 50 then "Pass" else "Fail"
@main def main(): Unit =
println(verdict(72))
println(verdict(30))Example
def grade(score: Int): String =
if score >= 50 then "Pass" else "Fail"
def show(text: String): Unit =
println(text)
@main def main(): Unit =
val result = grade(84)
println(result)
show("Check complete")Key points
- Last expression: The value of the last expression in a function body is the result the function gives back.
- Storing a result: A call can be assigned to a val, just like any other value.
- Unit: A function that only prints and gives back nothing has the result type Unit.
- If body: A function body can be a single if expression, so the result depends on a condition.
In this example, grade gives back "Pass" for a score of 84 because its body is an if expression. The call result is stored in the val result and printed on the next line. The show function then prints its message and gives back Unit, since it returns nothing.
Note
Scala needs no return keyword, because the last expression is already the result.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
A def ends with the line total alone, after working out val total = a + b. What does the def give back?