我正在实现获取随机索引并返回元组随机索引处的元素的函数。
我知道对于像这样的元组,
val a=(1,2,3)
a._1=2
但是,当我使用随机索引
val index=random_index(integer that is smaller than size of tuple)
时,a._index
不起作用。
如果你只在运行时知道
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
虽然这个
a(1)
似乎与标准a._1
非常相似。
从 Scala 3 开始,可以使用
apply
方法以类型安全的方式访问元组元素(只要在编译时知道索引):
val a = (1, 2, 3)
val secondEl = a(1) // result: 2