I've been shown a weird snippet in Scala which I don't quite understand. To me, assignments in Scala return Unit, unlike in Java where it returns the type of the variable which has been affected a value. However, let's consider this class :
case class C(i: Int) { def f = C(i = i + 10) } This compiles completely fine, which is pretty weird ! The factory method C.apply expects an Int, whereas I pass it what seems to be an assignment, of type Unit. By the way if I remove the assignment to just let the expression, it seems to have the exact same behaviour.
Let's try this now :
case class C(i: Int) { def f = { i = i + 10 C(i = i + 10) } } Ok now this is the world I know : i is a val, then you cannot mutate it so i = i + 10 does not compile. However, C(i = i + 10) still compiles without complaining. What is this weirdness ? Is there a reason for thatto exist ?