问题
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