0

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

println("foo"+r.nextInt(2))

gives foo0 or foo1 when I would like 10 or 5

2 Answers 2

2

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:

foos.apply(r.nextInt(2))

scala> foos(r.nextInt(2))
res20: Int = 5
Sign up to request clarification or add additional context in comments.

Comments

2

That doesn't work in a statically typed language. Pretty sure it's bad practice in any dynamic language too.

Try:

List(foo0, foo1)(r.nextInt(2))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.