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,

asked Apr 10, 2018 at 3:38
2
  • Having a mutable reference does not make the object mutable. Using var in this case just means you can do pair = some_other_tuple Commented Apr 10, 2018 at 3:40
  • thanks, and some_other_tuple has to be same type as pair Commented Apr 10, 2018 at 3:48

2 Answers 2

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
answered Apr 10, 2018 at 6:08
Sign up to request clarification or add additional context in comments.

Comments

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)
answered Apr 10, 2018 at 3:54

1 Comment

how about pair = pair.copy(_1=89), :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.