2

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?

Johnny
  • 14,397
  • 15
  • 77
  • 118

1 Answers1

4

Because assignment in Scala evaluates to Unit, as can be demonstrated:

Welcome to Scala 2.12.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_112).
Type in expressions for evaluation. Or try :help.

scala> val y = { val x = 4 }
y: Unit = ()

Note that this is different to Java:

jshell> int x, y
x ==> 0
y ==> 0

jshell> x = (y = 4)
x ==> 4

Why scala chose this has been answered before

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • While related, I think Java example `x = (y = 4)` is not the same as Scala `val y = { val x = 4 }`. Java `int y = 4` is not even expression, it certainly does not return a value of `y`. – Suma Oct 26 '17 at 15:05
  • Thanks, the answer you linked to was exactly what I needed. I have elaborated the q in express this knowledge and the root for my confusion. https://stackoverflow.com/questions/1998724/what-is-the-motivation-for-scala-assignment-evaluating-to-unit-rather-than-the-v – Johnny Oct 26 '17 at 15:22
  • @Suma - I don't really understand your point; at what point did I write `int y = 4`? – oxbow_lakes Oct 27 '17 at 13:28