在 Scala 中,如何访问元组中的特定索引? [英] In scala, how do I get access to specific index in tuple?

查看:31
本文介绍了在 Scala 中,如何访问元组中的特定索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现获取随机索引并返回元组随机索引处的元素的函数.

I am implementing function that gets random index and returns the element at random index of tuple.

我知道对于元组,val a=(1,2,3) a._1=2

但是,当我使用随机索引val index=random_index(小于元组大小的整数)时,a._index不起作用.

However, when I use random index val index=random_index(integer that is smaller than size of tuple), a._index doesnt work.

推荐答案

您可以使用 productElement,注意它是从零开始的,并且返回类型为Any:

val a=(1,2,3)
a.productElement(1) // returns 2nd element

这篇关于在 Scala 中,如何访问元组中的特定索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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