In scala, how do I get access to specific index in tuple?

三世轮回 提交于 2020-12-15 06:24:50

问题


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

I know that for tuple like, val a=(1,2,3) a._1=2

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


回答1:


You can use productElement, note that it is zero based and has return type of Any:

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



回答2:


If you know random_index only at runtime the best what you can have is (as @GuruStron answered)

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

If you know random_index at compile time you can do

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

Although this a(1) seems to be pretty similar to standard a._1.



来源:https://stackoverflow.com/questions/64121418/in-scala-how-do-i-get-access-to-specific-index-in-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!