shanlodh
shanlodh

Reputation: 1045

Scala: tuples as var

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,

Upvotes: 0

Views: 323

Answers (2)

J0HN
J0HN

Reputation: 26961

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

Upvotes: 2

user unknown
user unknown

Reputation: 36269

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)

Upvotes: 1

Related Questions