vdep
vdep

Reputation: 3590

How to get value of variables in Scala, where name of variable is obtained as string

i have existing variables:

scala> a
res69: Double = 5.0

scala> b
res70: Double = 10.0

scala> c
res71: Double = 15.0

There is a list containing variable names as string like:

scala> val variableList = List("a","b","c")
variableList: List[String] = List(a, b, c)

How to get values of variables in this list. I am expecting output as:

List(5.0, 10.0, 15.0) 

Upvotes: 1

Views: 1142

Answers (1)

Shyamendra Solanki
Shyamendra Solanki

Reputation: 8851

if the scope of question is limited to getting values of terms defined in scala REPL, following works:

> val a = 5.0
> val b = 10.0
> val c = 15.0
> val variableList = List("a", "b", "c")
> variableList.map(v => $intp.valueOfTerm(v).getOrElse("Undefined: " + v))
// List[AnyRef] = List(5.0, 10.0, 15.0)

$intp is the REPL's interpreter.IMain object.

Upvotes: 3

Related Questions