EDIT: 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.
I would like to do following in Scala ...
def save(srcPath: String, destPath: String) {
if (!destPath.endsWith('/'))
destPath += '/'
// do something
}
... but I can't beacuse destPath
is a val. Is there any way to declare destPath
as var?
Note: there are similar questions but in all of them OP just wanted to modify array.
Please do not advise following:
Mutating the input parameters is often seen as bad style and makes it harder to reason about code.
I think it's valid in imperative programming (Scala allows both, right?) and adding something like tmpDestPath
would just add clutter.
EDIT: 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 don't have to create new variable and i don't have to compute i+1 twice.
++
operator(s) for numerical types. Such things reek of a non-functional, side-effect-oriented programming style, which is something that Scala generally encourages you to avoid. As it stands, if you want to repeatedly mutate a function parameter, you must first store it into avar
, which makes your intentions clearer, anyway! – Destin++
. The problem with++
is that it cannot be implemented as a method of a class -- it would have to be a language feature built in the compiler, and specific to certain types. – Daniel C. Sobral