如何在父类的数据集中返回子类对象?下面的代码编译,但最后一行在运行时失败“scala.ScalaReflectionException:不是一个术语”。任何帮助都非常感谢。
案例类Apple和Orange扩展了Fruit特性。我试图在Fruit ref中返回Apple和Orange的对象。
import org.apache.spark.sql._
object Test {
case class Item(name: String, itemType: Int, count: Long)
trait Fruit extends Product{
def name: String
def count: Long
}
case class Apple(name: String, count: Long) extends Fruit
case class Orange(name: String, count: Long) extends Fruit
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder
.master("local[2]")
.getOrCreate()
import spark.implicits._
val ds = Seq(("apple", 1, 1), ("orange", 2, 1))
.toDF("name", "itemType", "count").as[Item]
ds.map(createFruits).show
}
def createFruits(item: Item): Fruit ={
item.itemType match{
case 1 => Apple(item.name, item.count)
case 2 => Orange(item.name, item.count)
}
}
}