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


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"

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

Need Your Help

how to write django test meant to fail?

django testing tdd

I have a model called Thing with an attribute called name, and I want name to be a char field that's only 3 characters long.

JavaScript equivalent of PhP preg_split

php javascript phpjs

Is there an equivalent of the PhP function preg_split for JavaScript?