Generally, in Scala the return keyword is not required when returning a value and the last value is always the return value.
For example:
def sum(a: Int, b: Int): Int = {
a + b
}
Will return and Int
of a+b
.
But, why when assigning the sum to another val
it won't be considered as a return value?
For example:
def sum(a: Int, b: Int): Int = {
val sum = a + b
}
Will show type mismatch error (expected Int
, got Unit
). What is the reason / logic behind this behavior?
Edit: As I learned from the comments and the answers, it's not that Scala last val is not the return value, it is the return value. But, val assignment returns Unit
and not the assigned type. The reason for this is: What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?