我有一个私有方法,用于声明和定义变量:
private def createDF() = {
val df = spark.read.avro("fileA")
}
如何从同一类中的另一个方法访问此val df?
答案 0 :(得分:0)
您不能直接在函数中声明的变量具有函数作用域,并且仅在函数内部可见。
如果要重用该变量,则需要将其设置为类变量:
class MyClass {
private var df: Option[DataFrame] = None
private def createDF() = {
this.df = Some(spark.read.avro("fileA"))
}
def otherFunction() = {
this.df.map(df => ...)
}
}
我在这里使用Option
来避免NullPointerException
在变量尚未初始化的情况下使用null
时可能会到达
答案 1 :(得分:-1)
您无法从df
访问otherFunction
,因为它是在createDF
范围内声明的。我会像这样更改它。
def createDF() = {
spark.read.avro("fileA")
}
def otherFunction(create: () => DataFrame) = {
val df = create()
...
}
然后以otherFunction
的身份呼叫otherFunction(createDF)
。另一种使用隐式的方法...
implicit val df = createDF()
def otherFunction(implicit df: DataFrame) = {
...
}