有没有办法让参数为 var 而不是 val?
在 Java 中调试命令行参数处理时,我习惯这样做
args = new String[] { "some", "new", "arguments" };
(如果您经常更改文件名作为参数,但又不想在 IDE 中浏览某些对话框窗口,则特别有用)。这样做的好处是我可以在构建版本时简单地注释掉该行。
所以当我在 Scala 中尝试这个时,我发现参数是 val 。 (而且我不能在参数前面写var
)。
- Q1:这样做的理由是什么?
Q2:那么除了这样做之外还有什么明显的解决方法
val newArgs = if (...) args else Array("some", "new", "arguments")
并在剩余的主方法中坚持使用
newArgs
?
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 val
s. (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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Q1: 改变输入参数通常被视为不好的风格,并且会使代码推理变得更加困难。
Q2:您可以在使用
args
执行任何操作之前将其分配给var
。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 avar
before doing anything with it.数组是可变的,所以如果你坚持:
当然,只有在传递的数组中有足够的空间时,这才有效。
请记住,您可以使用 Scala 中的默认参数以更简洁的方式解决原始问题。Arrays are mutable, so if you insist:
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.如果您只想修改函数内部的参数,那么描述中的方法就足够了。
但是,如果您需要将其视为真正的“引用”类型并保持修改在函数外部有效,您可以将参数包装在案例类中,例如:
并像这样使用它:
然后,当您使用 refInt 时.value 在函数之外,它仍然是 3。
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.:
And use it like:
Then, when you use
refInt.value
outside the function, it would still be 3.