scala - 在scala中动态创建变量

标签 scala azure apache-spark variables databricks

我有一个 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/

相关文章:

scala - Scala 中参数化类型的运算符

scala - 返回存在类型有意义吗?

azure - 取消注册 Azure 资源提供程序功能

sql - 在 Scala Spark 的 for 循环中生成数据帧导致内存不足

scala - 执行器占用的内存超出了定义

scala - 如何设计 Spark 应用,让 Shuffle 数据在一些迭代后自动清理

azure - 在函数应用程序中,比例单位是函数还是应用程序?

Azure Active Directory - 用户的组声明不是最新的

scala - 循环遍历 Map Spark Scala

xml - 在 Scala 中向 XML 文件添加或附加新元素而不是替换它