java - 访问 Scala 变量:“未找到值:variable_name”问题
问题描述
我有两个 Scala 对象。
- common_code
- 依赖代码
在 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
其他对象中的变量吗?
解决方案
这里重要的一件事是您无法访问位于方法内部的字段。您不应该在最后一行分配一个变量 (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_method
从common_code
对象调用,结果被分配给一个名为tableName
. 然后依次tableName
用于字符串插值。
还有几个建议:
推荐阅读
- python - 如果我将 tkinter 对象放在函数中,为什么 x 和 y 坐标不会与您单击的位置对齐?
- regex - 是否可以在不使用 OR 的情况下将两个正则表达式模式组合成一个?, 管道字符
- google-play-services - Google Play 知识产权政策;为什么他们实际上首先接受侵犯版权?
- visual-studio-code - 无法安装 VisualStudioCode 自定义主题 (.vsix)
- azure - 特定 Blob 存储的 Azure 事件主题筛选
- java - 我无法从 json 的主表中获取字段
- matlab - 采样图像
- bash - 如何使用 Curl 显示进度条制作 Bash 脚本
- django - 无法通过 DRF 上传文件
- java - 使用递归打印二进制