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

查看:161
本文介绍了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天全站免登陆