Scala - 可变(var)方法参数参考 [英] Scala - mutable (var) method parameter reference

查看:24
本文介绍了Scala - 可变(var)方法参数参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里不断获得赞成票.只是为了记录,我不再认为这很重要.自从我发布后我就不需要它了.

I keep getting upvotes here. Just for the record, I no longer think this is important. I haven't needed it since I posted it.

我想在 Scala 中执行以下操作...

I would like to do following in Scala ...

def save(srcPath: String, destPath: String) {
    if (!destPath.endsWith('/'))
        destPath += '/'
    // do something
}

...但我不能因为 destPath 是一个 val.有没有办法将 destPath 声明为 var?

... but I can't beacuse destPath is a val. Is there any way to declare destPath as var?

注意:有类似的问题,但在所有这些问题中,OP只是想修改数组.

Note: there are similar questions but in all of them OP just wanted to modify array.

请不要建议以下内容:

改变输入参数通常被视为不好的风格,并使其成为更难对代码进行推理.

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

我认为它在命令式编程中是有效的(Scala 允许两者,对吧?)并且添加诸如 tmpDestPath 之类的东西只会增加混乱.

I think it's valid in imperative programming (Scala allows both, right?) and adding something like tmpDestPath would just add clutter.

不要误解.我知道字符串是不可变的,我不想引用引用,因为我不想修改调用者的数据.我只想修改调用者给我的字符串的本地引用(例如,orig + '/').我只想在当前方法的范围内修改该值.看,这在 Java 中完全有效:

Don't misunderstand. I know that strings aren't mutable and I don't want a reference to reference because I don't want to modify data of caller. I just want to modify local reference to string that caller gave me with my string (eg. orig + '/'). I want to modify that value only in scope of current method. Look, this is perfectly valid in Java:

void printPlusOne(int i) {
    i++;
    System.out.println("i is: " + i);
    System.out.println("and now it's same: " + i);
}

我不必创建新变量,也不必计算 i+1 两次.

I don't have to create new variable and i don't have to compute i+1 twice.

推荐答案

你不能.

您必须声明一个额外的 var(或使用更实用的样式 :-)).

You'll have to declare an extra var (or use a more functional style :-)).

简单的例子:

def save(srcPath: String, destPath: String) {
    val normalizedDestPath =
      if (destPath.endsWith('/')) destPath
      else destPath + '/'
    // do something with normalizedDestPath 
}

这篇关于Scala - 可变(var)方法参数参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆