为什么隐式类中的函数不可用?

时间:2018-05-22 22:12:19

标签: scala scala-implicits

我正在尝试自学Scala并使用IntelliJ IDEA作为我的IDE。我已经启动了IntelliJ的sbt shell,运行console然后输入以下内容:

import org.apache.spark.SparkConf
import org.apache.spark.sql.{DataFrame, SparkSession}
import java.time.LocalDate
object DataFrameExtensions {
  implicit class DataFrameExtensions(df: DataFrame){
    def featuresGroup1(groupBy: Seq[String], asAt: LocalDate): DataFrame = {df}
    def featuresGroup2(groupBy: Seq[String], asAt: LocalDate): DataFrame = {df}
  }
}
import DataFrameExtensions._
val spark = SparkSession.builder().config(new SparkConf().setMaster("local[*]")).enableHiveSupport().getOrCreate()
import spark.implicits._
val df = Seq((8, "bat"),(64, "mouse"),(-27, "horse")).toDF("number", "word")
val groupBy = Seq("a","b")
val asAt = LocalDate.now()
val dataFrames = Seq(df.featuresGroup1(groupBy, asAt),df.featuresGroup2(groupBy, asAt))

在最后一行失败:

scala> val dataFrames = Seq(df.featuresGroup1(groupBy, asAt),df.featuresGroup2(groupBy, asAt))
<console>:25: error: value featuresGroup1 is not a member of 
org.apache.spark.sql.DataFrame
       val dataFrames = Seq(df.featuresGroup1(groupBy, asAt),df.featuresGroup2(groupBy, asAt))
                               ^
<console>:25: error: value featuresGroup2 is not a member of org.apache.spark.sql.DataFrame
   val dataFrames = Seq(df.featuresGroup1(groupBy, asAt),df.featuresGroup2(groupBy, asAt))
                                                            ^

我从其他地方(我知道它工作的地方)几乎逐字复制了代码,所以我不知道为什么这不起作用。为什么隐式类中定义的函数不能作为DataFrame上的函数?

2 个答案:

答案 0 :(得分:3)

您似乎需要将implicit class DataFrameExtensions重命名为不同的名称,因为object具有相同的名称。我想编译器在使用

时很难找到implicit class
import DataFrameExtensions._

我将它重命名为下面,现在可以正常使用

 implicit class FeatureGroupImplicits(df: DataFrame){
    def featuresGroup1(groupBy: Seq[String], asAt: LocalDate): DataFrame = {df}
    def featuresGroup2(groupBy: Seq[String], asAt: LocalDate): DataFrame = {df}
  }

答案 1 :(得分:1)

(编辑问题,回答过时,可能稍后编辑)

这里:

val groupBy = Seq('a','b')

生成Seq[Char],而不是Seq[String] ..由于featuresGroup1(s: Seq[Char], d: LocalDate)上没有方法DataFrame,scalac会尝试查找到具有此方法的类的隐式转换。但是,只有

def featuresGroup1(groupBy: Seq[String], asAt: LocalDate): DataFrame

因此Seq[Char]Seq[String]并不合适,编译器甚至无法报告类似

的内容
  

方法featuresGroup1的错误参数类型      预期:Seq [String]      收到:Seq [Char]

因为它根本没有看到与此方法的任何关联。

改为使用Seq("a", "b")