迭代一个元组 [英] Iterate Over a tuple

查看:222
本文介绍了迭代一个元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个带有元组并返回Map
的泛型方法示例:

I need to implement a generic method that takes a tuple and returns a Map Example :

val tuple=((1,2),(("A","B"),("C",3)),4)

我一直试图将这个元组分解为一个列表:

I have been trying to break this tuple into a list :

val list=tuple.productIterator.toList
Scala>list: List[Any] = List((1,2), ((A,B),(C,3)), 4)

但是这种方式会返回List [Any]。

But this way returns List[Any] .

我正在尝试找出来如何迭代以下元组,例如:

I am trying now to find out how to iterate over the following tuple ,for example :

((1,2),(("A","B"),("C",3)),4)

以循环每个元素1,2,A,B,......等。我怎样才能对元组进行这种迭代

in order to loop over each element 1,2,"A",B",...etc. How could I do this kind of iteration over the tuple

推荐答案

怎么样?:

def flatProduct(t: Product): Iterator[Any] = t.productIterator.flatMap {
  case p: Product => flatProduct(p)
  case x => Iterator(x)
}
val tuple = ((1,2),(("A","B"),("C",3)),4)
flatProduct(tuple).mkString(",") // 1,2,A,B,C,3,4

好的,任何 -problem仍然存在。至少是由于返回类型为 productIterator

Ok, the Any-problem remains. At least that´s due to the return type of productIterator.

这篇关于迭代一个元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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