我有一个 list
w: 列表[任意] = 列表(A, B, C)
我想动态创建一个变量
for (e <- w) {
//val $e = notebook.filter(s"Name='$e'").select("Location")
println(e)
}
因此应该创建三个变量 A、B、C 及其相应的位置值。
感谢任何帮助,谢谢
最佳答案
您可以创建变量列表
val List(e1, e2, e3) = w.map { e =>
println(e)
notebook.filter(s"Name='$e'").select("Location")
}
或
val es = w.map { e =>
println(e)
notebook.filter(s"Name='$e'").select("Location")
}
并使用变量 (val
s) e1
、e2
、e3
或 es(0 )
、es(1)
、es(2)
。
i want the variable to have the same value as name. I would want to use tht variables in other part of the code
然后你可以使用macro annotation
import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
@compileTimeOnly("enable macro annotations")
class generateVariables(names: String*) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro GenerateVariablesMacro.impl
}
object GenerateVariablesMacro {
def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
val names = c.prefix.tree match {
case q"new generateVariables(..$ns)" => ns
}
val variables = names.map { case q"${name: String}" =>
q"""val ${TermName(name)} = notebook.filter(${s"Name='$name'"}).select("Location")"""
}
annottees match {
case q"$mods object $tname extends { ..$earlydefns } with ..$parents { $self => ..$body }" :: Nil =>
q"""$mods object $tname extends { ..$earlydefns } with ..$parents { $self =>
..$variables
..$body
}"""
}
}
}
用法:
@generateVariables("A", "B", "C")
object X
//scalac: object X extends scala.AnyRef {
// def <init>() = {
// super.<init>();
// ()
// };
// val A = notebook.filter("Name=\'A\'").select("Location");
// val B = notebook.filter("Name=\'B\'").select("Location");
// val C = notebook.filter("Name=\'C\'").select("Location")
//}
现在您可以使用变量X.A
、X.B
、X.C
(或者如果您导入X._
,则只是A
、B
、C
)。
关于scala - 在scala中动态创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64010425/