Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala generic (tuple) type with multiple subtypes

I am writing a data structure (basically a hashmap) in Scala that will take one tuple (of possibly different number of arguments each time) and do something with it. To generically implement this, I defined a type:

type T <: Tuple1[_] with Tuple2[_,_] with Tuple3[_,_,_] with Tuple4[_,_,_,_] with Tuple5[_,_,_,_,_]

and then the data structure

val map = new HashMap[Int, T]

But this is ugly, since I have to change the type every time I have to handle more arguments in a tuple. Is there to define a generic tuple type?

Thanks, Y.K.

like image 955
Y.K. Avatar asked Sep 13 '25 10:09

Y.K.


1 Answers

The first solution is to use Product, as said by @om-nom-nom. Indeed, it's the only common supertype of all tuples.

val map = Map.empty[Int, Product]
map + (2 -> ("a", "b"))

And then to use the methods productArity, productElement and productIterator to handle the returned value.

You can also use a map of list (or any indexed collection).

val map = Map.empty[Int, List[_]]
map + (3 -> ("a" :: "b" :: "c" :: Nil))
map + (2 -> List("a", "b"))

The last solution is not that convenient for the user, but at least you know exactly what collection you handle. You could also add an implicit.

like image 130
Lomig Mégard Avatar answered Sep 15 '25 03:09

Lomig Mégard