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
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable.
If you're new to functional programming, a Tuple is a group or collection of data -- it can contain two elements or more. Spark is written in Scala, which supports tuples.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With