首页 > 解决方案 > 访问 Scala 变量:“未找到值:variable_name”问题

问题描述

我有两个 Scala 对象。

  1. common_code
  2. 依赖代码

在 common_code 中,我有一种方法可以编写我的通用代码并声明一些变量。我想在我的第二个对象中使用这些变量和代码,但是当我尝试访问这些变量时,我得到 common_method not found value: variable name issue。

我正在使用下面的代码。

object comman_code{
    def common_method(args: Array[String]) {
        val properties: Properties = new Properties()
        val hdfsConf = new Configuration();
        val fs: FileSystem = FileSystem.get(hdfsConf);
        val is = fs.open(new Path(args(0)));
        properties.load(is)
        //created sparkSesssion

        //Table_Name i want to use in 2nd program
        val Table_Name = properties.getProperty("Table_Name") 
    }
}

object dependent_code {
    def main(args: Array[String]):Unit = {
        val common_method = helper_class.common_method(args)
        val mydf=sparksesssion.sql(s"select * from ${Table_Name}").show() //not able to acess getting not found value: Table_Name
    }
}

有人可以建议我如何访问Table_Name其他对象中的变量吗?

标签: javascalaapache-spark

解决方案


这里重要的一件事是您无法访问位于方法内部的字段。您不应该在最后一行分配一个变量 (val Table_Name) common_method,而是返回它。否则你的方法是 just Unit,这意味着调用后什么都不会返回。这是您可以尝试理解的一点改进:


object comman_code {
  def common_method(args: Array[String]): String = {
    val properties: Properties = new Properties()
    val hdfsConf = new Configuration();
    val fs: FileSystem = FileSystem.get(hdfsConf);
    val is = fs.open(new Path(args(0)));
    properties.load(is)
    //created sparksesssion
    properties.getProperty("Table_Name")
  }
}

object dependent_code {
  def main(args: Array[String]): Unit = {
    val tableName = comman_code.common_method(args)
    val mydf = sparksesssion.sql(s"select * from $tableName").show() 
  }
}

注意:我common_methodcommon_code对象调用,结果被分配给一个名为tableName. 然后依次tableName用于字符串插值。

还有几个建议:

  1. 命名约定
  2. 如何发布问题

推荐阅读