3

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 ?

1 Answer 1

8

This is because, in the case of C(i = i + 10) the left-hand i is not the field C#i but a named parameter. No assignment is being done at all.

C(i = i + 10) ^ ^ +---|-------- Parameter name | +- - - - - - - - - - - - - - Reference to the field `i` in the instance of the class `C` 

Some places where named parameters make sense:

  • Avoiding the "what does this {boolean, integer} mean" moment:

    someMethod(anObject, flagName=true) // As opposed to someMethod(anObject, true) ... what's `true` for? anotherMethod(arg1, arg2, totalMagic=33) 
  • When using default values for parameters (to invoke the right constructor):

    def withDefaults(i: Int, flag: Boolean = true, wrapper: Option[String] = None) = { wrapper.fold(s"$i with $flag")(_.format(i, flag)) } withDefaults(3, Some("stuff %s around %s")) // won't compile // error: type mismatch; // found : Some[String] // required: Boolean withDefaults(3, wrapper = Some("stuff %s around %s")) // works (returns "stuff 3 around true") 
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, right I did not know this syntax. Is there any advantage to do this ? I just tried using it and it allows, for example, to pass the parameters in a random order which I don't find really good as quite often the order of the parameters has some semantic
@Dici - updated with some examples of why you might use it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.