Scala - mutable (var) method parameter reference

后端 未结 7 1436
天命终不由人
天命终不由人 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 07:02

    The JVM does not allow pass-by-reference of pointers to objects (which is how you'd do this in C++), so you can't do exactly what you want.

    One option is to return the new value:

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

    Another is to create a wrapper:

    case class Mut[A](var value: A) {}
    
    def save(srcPath: String, destPath: Mut[String]) {
      if (!destPath.value.endsWith("/")) destPath.value += '/'
      // do something
    }
    

    which users will then have to use on the way in. (Of course, they'll be tempted to save("/here",Mut("/there")) which will throw away the alterations, but this is always the case with pass-by-reference function arguments.)


    Edit: what you're proposing is one of the biggest sources of confusion among non-expert programmers. That is, when you modify the argument of a function, are you modifying a local copy (pass-by-value) or the original (pass-by-reference)? If you cannot even modify it it is pretty clear that anything you do is a local copy.

    Just do it that way.

    val destWithSlash = destPath + (if (!destPath.endsWith("/")) "/" else "")
    

    It's worth the lack of confusion about what is actually going on.

提交回复
热议问题