簡體   English   中英

無法從 class (Scala) 調用 function

[英]Not able to call function from class (Scala)

我只是想從我在 Scala 中創建的 class(在 databricks 筆記本中)調用一個方法。 不要擔心中間的所有代碼。 只需關注最底部的SecondExplode class 和registerUDF function。 class如下:

case class SecondExplodeTimes(start_dt: String, end_dt: String, counter: Int)



class SecondExplode extends Serializable {
     def expandDatetimeRangeToStartAndEndSeconds(start: String, end: String, ceilingLimit: Int): Seq[SecondExplodeTimes] =
    {

      val start_time: DateTime = DateTime.parse(start, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))

      val end_time: DateTime = DateTime.parse(end, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))

      val secBetween = end_time.getSecondOfMinute - start_time.getSecondOfMinute

      (1 to secBetween).zipWithIndex.map{case (p, counter) => {
       val strt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").print(start_time.plusSeconds(p-1))
       val endt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").print(start_time.plusSeconds(p))
       SecondExplodeTimes(strt, endt, counter)
      }}.toSeq
    }

    def registerUDF: UserDefinedFunction = {
      val spark = SparkSession.builder().getOrCreate()
      spark.udf.register("second_explode", expandDatetimeRangeToStartAndEndSeconds _)
    }
}

在下一個單元格中調用 class 和 function

val secondexplode = new SecondExplode.registerUDF

我收到此錯誤:

error: not found: value SecondExplode. val secondexplode = new SecondExplode.registerUDF

我相信我使用的是 Scala 2 版本,所以語法是正確的。 簡單地說,我試圖從SecondExplode class 中調用registerUDF function 來測試它是否真的有效。 先感謝您。

我相信你想要的是(new SecondExplode).registerUDF

問題在於解析優先級。 . 優先級高於new 編譯器假定您正在嘗試創建SecondExplode.registerUDFnew實例,而不是創建new SecondExplode然后在實例上調用registerUDF方法。

這可能是一種誤解的原因是沒有什么可以阻止您這樣做:

object SecondExplode {
  class registerUDF {}
}

在這種情況下, new SecondExplode.registerUDF會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM