Is there a way to let arguments be var instead of val?
Asked Answered
O

3

9

When debugging command line argument handling in Java I'm used to doing

args = new String[] { "some", "new", "arguments" };

(especially useful if have a filename as argument which you frequently change, but don't want to go through some dialog windows in the IDE). This has the benefit that I can simply comment out the line when building a release.

So when I tried this in Scala I discovered that arguments are vals. (And I can't write var in front of the parameter).

  • Q1: What's the rationale for this?
  • Q2: So is there any obvious work-around except for doing

    val newArgs = if (...) args else Array("some", "new", "arguments")
    

    and stick to newArgs in the remaining main method?

Open answered 17/3, 2011 at 8:20 Comment(0)
C
13

Q1: Mutating the input parameters is often seen as bad style and makes it harder to reason about code.

Q2: You could assign the args to a var before doing anything with it.

Crowell answered 17/3, 2011 at 8:22 Comment(1)
Q1, good point. Q2, yes. That's better than the if-line, because then I can simply comment out the reassignment as in the case of Java. Thanks!Open
C
1

Arrays are mutable, so if you insist:

Seq("some", "new", "arguments").copyToArray(args, 0, 3)

That does, of course, only work if there is enough space in the passed array.

Remember that you can use default parameters in Scala to solve your original probem in a much cleaner way.

Celestina answered 17/3, 2011 at 12:12 Comment(2)
Could you give an example of such default parameter for the main method?Open
Ah, sorry, got carried away there. Does not work since in case of no parameters, an empty array is passed. Maybe that might be worth a change.Celestina
R
0

If you only want to modify the args inside of the function, then your approach in the description is enough.

However, if you need to treat it as a true "reference" type and keep the modifications valid outside the function, you can wrap the arguments in a case class, e.g.:

case class Ref[A](var value: A)

And use it like:

def modify(refInt: Ref[Int]) = refInt.value = 3

Then, when you use refInt.value outside the function, it would still be 3.

Rake answered 7/10, 2017 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.