Tuples are immutable in Scala, so why is it even allowed to declare a tuple as a var and not always val?
var pair = (99, "Luftballons")
println(pair._1) // Ok
pair._1 = 89 // <console>:14: error: reassignment to val
Using ScalaIDE Eclipse, Windows 10
Thanks,
2 Answers 2
There's a difference between mutable data structures and mutable references - see this answer for details.
In this particular case, you're using mutable reference to immutable data structure, which means you can only replace it with completely different one. This would work:
var pair = (99, "Luftballons")
println(pair._1) // Ok
pair = (100, "Luftballons") // OK
As others already pointed out there's a convenience method copy
defined for Tuple
, which allows creating a copy of an object (potentially replacing some fields).
pair = pair.copy(5, "Kittens") // OK
Comments
You have to update your pair like this:
pair = (89, pair._2)
pair: (Int, String) = (89,Luftballons)
by a new assignment to the pair, not to the underlying tuple. Or you use pair.copy, like suggested by chengpohi.
scala> pair = pair.copy(_1=101)
pair: (Int, String) = (101,Luftballons)
1 Comment
pair = pair.copy(_1=89)
, :)
pair = some_other_tuple