具有多个子类型的Scala通用(元组)类型 [英] Scala generic (tuple) type with multiple subtypes

查看:148
本文介绍了具有多个子类型的Scala通用(元组)类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Scala中编写一个数据结构(基本上是一个HashMap),它将采用一个元组(每次可能有不同数量的参数)并对其进行处理。为了一般地实现这个,我定义了一个类型:

  type T <:Tuple1 [_] with Tuple2 [_,_]带有Tuple5 [_,_,_,_,_]的Tuple3 [_,_,_]与Tuple4 [_,_,_,_] 

然后是数据结构

  val map = new HashMap [Int,T ] 

但这很丑陋,因为每次必须处理更多参数在一个元组中。是否有定义一个通用的元组类型?



谢谢,
YK

解决方案

第一个解决方案是使用 Product ,如@ om-nom-nom所述。确实,它是所有元组中唯一的超类型。

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

然后使用方法 productArity productElement productIterator 来处理返回值。

您也可以使用列表(或任何索引集合)的地图。

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

最后的解决方案对用户来说并不方便,但至少您确切知道您处理的是什么样的集合。您也可以添加一个隐式。


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.

解决方案

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.

这篇关于具有多个子类型的Scala通用(元组)类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆