gpt4 book ai didi

scala - 在scala中动态创建变量

转载 作者:行者123 更新时间:2023-12-03 02:33:46 26 4
gpt4 key购买 nike

我有一个 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")
}

并使用变量 (vals) e1e2e3es(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.AX.BX.C(或者如果您导入X._,则只是ABC)。

关于scala - 在scala中动态创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64010425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com