deltanovember
deltanovember

Reputation: 44091

In Scala, how can I reassign tuple values?

I'm trying to do something like the following

var tuple = (1, "test")
tuple._2 = "new"

However this does not compile it complains about val

Upvotes: 17

Views: 14675

Answers (2)

Colliot
Colliot

Reputation: 1551

You can wrapper the component(s) you need to modify in a case class with a var member, like:

case class Ref[A](var value: A)

var tuple = (Ref(1), "test")
tuple._1.value = 2
println(tuple._1.value) // -> 2

Upvotes: 0

Rex Kerr
Rex Kerr

Reputation: 167921

You can't reassign tuple values. They're intentionally immutable: once you have created a tuple, you can be confident that it will never change. This is very useful for writing correct code!

But what if you want a different tuple? That's where the copy method comes in:

val tuple = (1, "test")
val another = tuple.copy(_2 = "new")

or if you really want to use a var to contain the tuple:

var tuple = (1, "test")
tuple = tuple.copy(_2 = "new")

Alternatively, if you really, really want your values to change individually, you can use a case class instead (probably with an implicit conversion so you can get a tuple when you need it):

case class Doublet[A,B](var _1: A, var _2: B) {}
implicit def doublet_to_tuple[A,B](db: Doublet[A,B]) = (db._1, db._2)
val doublet = Doublet(1, "test")
doublet._2 = "new"

Upvotes: 47

Related Questions