val-mutable versus var-immutable in Scala

后端 未结 5 2347
慢半拍i
慢半拍i 2020-11-27 10:40

Are there any guidelines in Scala on when to use val with a mutable collection versus using var with an immutable collection? Or should you really aim for val with an immuta

5条回答
  •  天涯浪人
    2020-11-27 11:07

    var immutable vs. val mutable

    In addition to many excellent answers to this question. Here is a simple example, that illustrates potential dangers of val mutable:

    Mutable objects can be modified inside methods, that take them as parameters, while reassignment is not allowed.

    import scala.collection.mutable.ArrayBuffer
    
    object MyObject {
        def main(args: Array[String]) {
    
            val a = ArrayBuffer(1,2,3,4)
            silly(a)
            println(a) // a has been modified here
        }
    
        def silly(a: ArrayBuffer[Int]): Unit = {
            a += 10
            println(s"length: ${a.length}")
        }
    }
    

    Result:

    length: 5
    ArrayBuffer(1, 2, 3, 4, 10)
    

    Something like this cannot happen with var immutable, because reassignment is not allowed:

    object MyObject {
        def main(args: Array[String]) {
            var v = Vector(1,2,3,4)
            silly(v)
            println(v)
        }
    
        def silly(v: Vector[Int]): Unit = {
            v = v :+ 10 // This line is not valid
            println(s"length of v: ${v.length}")
        }
    }
    

    Results in:

    error: reassignment to val
    

    Since function parameters are treated as val this reassignment is not allowed.

提交回复
热议问题