Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how can I reassign tuple values?

Tags:

scala

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

like image 322
deltanovember Avatar asked Aug 22 '11 03:08

deltanovember


People also ask

Can you change elements in a tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

Is tuple mutable in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable.

What is tuple in spark?

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.


1 Answers

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"
like image 64
Rex Kerr Avatar answered Sep 29 '22 05:09

Rex Kerr