在scala中,如何访问元组中的特定索引?

问题描述 投票:0回答:3

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

我知道对于像这样的元组,

val a=(1,2,3)
a._1=2

但是,当我使用随机索引

val index=random_index(integer that is smaller than size of tuple)
时,
a._index
不起作用。

scala tuples
3个回答
6
投票

您可以使用

productElement
,请注意,它是从零开始的,并且返回类型为
Any

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

2
投票

如果你只在运行时知道

random_index
,那么你能拥有的最好的就是(如@GuruStron回答)

val a = (1,2,3)
val i = 1
val x = a.productElement(i)
x: Any // 2

如果你在编译时知道

random_index
,你就可以做到

import shapeless.syntax.std.tuple._
val a = (1,2,3)
val x = a(1)
x: Int // 2   // not just Any
// a(4) // doesn't compile
val i = 1
// a(i) // doesn't compile

https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#hlist-style-operations-on-standard-scala-tuples

虽然这个

a(1)
似乎与标准
a._1
非常相似。


0
投票

从 Scala 3 开始,可以使用

apply
方法以类型安全的方式访问元组元素(只要在编译时知道索引):

val a = (1, 2, 3)
val secondEl = a(1) // result: 2
© www.soinside.com 2019 - 2024. All rights reserved.