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
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.
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.
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”.
Shapeless now does it. Adding
import shapeless.syntax.std.tuple._
before your code just compiles.
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