Scala:在另一个方法中访问在一个方法内部声明的变量

时间:2018-10-10 20:37:52

标签: scala

我有一个私有方法,用于声明和定义变量:

private def createDF() = {
   val df = spark.read.avro("fileA")
}

如何从同一类中的另一个方法访问此val df?

2 个答案:

答案 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) = {
  ...
}
相关问题