【问题标题】:Scala cannot inferScala 无法推断
【发布时间】:2021-02-05 15:30:19
【问题描述】:

我有一个非常简单的 Spark 代码片段,它在 Scala 2.11 上运行,并在 2.12 之后停止编译。

import spark.implicits._
val ds = Seq("val").toDF("col1")

ds.foreachPartition(part => {
  part.foreach(println)
})

它失败并出现错误:

Error:(22, 12) value foreach is not a member of Object
  part.foreach(println)

解决方法是用这样的代码帮助编译器:

import spark.implicits._
val ds = Seq("val").toDF("col1")
println(ds.getClass)

ds.foreachPartition((part: Iterator[Row]) => {
  part.foreach(println)
})

有没有人能很好地解释为什么编译器不能将part 推断为Iterator[Row]

ds 是一个DataFrame,定义为type DataFrame = Dataset[Row]

foreachPartition 有两个签名:

  • def foreachPartition(f: Iterator[T] => Unit): Unit
  • def foreachPartition(func: ForeachPartitionFunction[T]): Unit

感谢您的帮助。

【问题讨论】:

  • 是因为2.12 Scala 提供了 SAM 支持,而 Spark API 不是为此而设计的,因此方法重载会产生歧义.而且由于 Spark 不再关心 Scala 用户,而是关心 JavaPython 用户,因此这可能永远无法解决。

标签: scala apache-spark type-inference


【解决方案1】:

这是为了帮助面临问题的人以及解决此问题的方法。

您可以将 Dataframe 转换为 rdd,然后使用 foreachpartition,您将能够编译和构建您的代码。

ds.rdd.foreachPartition(part => {
  part.foreach(println)
})

【讨论】:

    猜你喜欢
    • 2014-12-27
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多