如何在Scala中获取变量的值,其中变量的名称以字符串形式获得

时间:2016-04-07 12:12:02

标签: scala

我有现有变量:

scala> a
res69: Double = 5.0

scala> b
res70: Double = 10.0

scala> c
res71: Double = 15.0

有一个包含变量名称的列表,如:

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

如何获取此列表中的变量值。我期待输出为:

List(5.0, 10.0, 15.0) 

1 个答案:

答案 0 :(得分:3)

如果问题的范围仅限于获取scala REPL中定义的术语的值,则以下作品:

> 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是REPL的interpreter.IMain对象。