我試圖在一些 Spark Scala 代碼中撰寫一些抽象,但是在使用物件時遇到了一些問題。我正在使用 Spark 的Encoder例子,它用于將案例類轉換為資料庫模式,但我認為這個問題適用于任何背景關系系結。
這是我正在嘗試做的最小代碼示例:
package com.sample.myexample
import org.apache.spark.sql.Encoder
import scala.reflect.runtime.universe.TypeTag
case class MySparkSchema(id: String, value: Double)
abstract class MyTrait[T: TypeTag: Encoder]
object MyObject extends MyTrait[MySparkSchema]
失敗并出現以下編譯錯誤:
Unable to find encoder for type com.sample.myexample.MySparkSchema. An implicit Encoder[com.sample.myexample.MySparkSchema] is needed to store com.sample.myexample.MySparkSchema instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._ Support for serializing other types will be added in future releases.
我嘗試像這樣在物件中定義隱含證據:(匯入陳述句是 IntelliJ 建議的,但看起來有點奇怪)
import com.sample.myexample.MyObject.encoder
object MyObject extends MyTrait[MySparkSchema] {
implicit val encoder: Encoder[MySparkSchema] = Encoders.product[MySparkSchema]
}
失敗并顯示錯誤訊息
MyTrait.scala:13:25: super constructor cannot be passed a self reference unless parameter is declared by-name
我嘗試的另一件事是將物件轉換為類并向建構式提供隱式證據:
class MyObject(implicit evidence: Encoder[MySparkSchema]) extends MyTrait[MySparkSchema]
這編譯和作業正常,但代價是MyObject現在成為 a class。
問題:是否可以在擴展特征時為背景關系邊界提供隱含證據?還是隱含的證據迫使我創建一個建構式并class改為使用?
uj5u.com熱心網友回復:
您的第一個錯誤幾乎為您提供了解決方案,您必須為產品型別匯入spark.implicits._。
你可以這樣做:
val spark: SparkSession = SparkSession.builder().getOrCreate()
import spark.implicits._
完整示例
package com.sample.myexample
import org.apache.spark.sql.Encoder
import scala.reflect.runtime.universe.TypeTag
case class MySparkSchema(id: String, value: Double)
abstract class MyTrait[T: TypeTag: Encoder]
val spark: SparkSession = SparkSession.builder().getOrCreate()
import spark.implicits._
object MyObject extends MyTrait[MySparkSchema]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424401.html
上一篇:Akka型別的Actor單元測驗
下一篇:在Scala的可變串列中合并物件
