Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append or prepend an element to a tuple in Scala

I have a tuple and want to add an element without loosing type safety. This is what I want to achieve:

val tuple = ("", 1, 1f) // (String, Int, Float)  val newTuple:(String, Int, Float, Double) = tuple :+ 1d 
like image 312
EECOLOR Avatar asked Mar 11 '13 21:03

EECOLOR


People also ask

Can you append an element to a tuple?

You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples, You can't remove elements from a tuple, also because of their immutability.

How do you append data to a tuple?

In summary, tuples can't be simply modified like lists because of their immutable nature. The most extensive way to append to a tuple is to convert the tuple into a list. If the only addition needed is either at the start or the end of the tuple, then simple concatenation + can be used.

How do I append an element to a list in Scala?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.


1 Answers

Shapeless now does it. Adding

import shapeless.syntax.std.tuple._ 

before your code just compiles.

like image 198
Alex Archambault Avatar answered Sep 21 '22 18:09

Alex Archambault