Scala generic (tuple) type with multiple subtypes

99封情书 提交于 2019-12-05 20:23:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!