0

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,

shanlodh
  • 1,015
  • 2
  • 11
  • 30

2 Answers2

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
J0HN
  • 26,063
  • 5
  • 54
  • 85
1

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)
user unknown
  • 35,537
  • 11
  • 75
  • 121