Scala - mutable (var) method parameter reference

后端 未结 7 1447
天命终不由人
天命终不由人 2020-12-08 06:17

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

7条回答
  •  难免孤独
    2020-12-08 06:54

    String objects are immutable in Scala (and Java). The alternatives I can think of are:

    1. Return the result string as return value.
    2. Instead of using a String parameter, use a StringBuffer or StringBuilder, which are not immutable.

    In the second scenario you would have something like:

    def save(srcPath: String, destPath: StringBuilder) {
        if (!destPath.toString().endsWith("/"))
           destPath.append("/")
        // do something
        //
    }
    

    EDIT

    If I understand correctly, you want to use the argument as a local variable. You can't, because all method arguments are val's in Scala. The only thing to do is to copy it to a local variable first:

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

提交回复
热议问题