ulrich ulrich - 1 year ago 57
Scala Question

Using a variable in value name

How to call two val: foo1 and foo2 randomly.

I managed to generate the name as a string but how can I convert it into a value name to print the value rather than the name.

val r = scala.util.Random

val foo0 = 10
val foo1 = 5


gives foo0 or foo1 when I would like 10 or 5

Answer Source

You can technically do this with reflection, but you shouldn't.

class Foo {
  val foo0 = 10
  val foo1 = 5

val r = new scala.util.Random

scala> val foo = new Foo
foo: Foo = Foo@f5009c7

scala> foo.getClass.getDeclaredMethod("foo" + r.nextInt(2)).invoke(foo).asInstanceOf[Int]
res19: Int = 10

Again, we shouldn't do this. It will turn your code into a sprawling mess of a minefield.

If you ever find yourself naming things with indices like foo0, foo1, foo2, etc, that means they probably belong in a collection of some type.

val foos = List(10, 5)

Then you can access them by index using apply:


scala> foos(r.nextInt(2))
res20: Int = 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download