[英]How to pass a case class into a function parameter and get a schema accordingly?
the function which will return me the schema I made a function called getschema(MyCaseClass) which will return me the schema by encoding using Encoders.product[MyCaseClass].schema but Encoders.product is not taking that case class as a parameter. 该函数将返回我的架构,我创建了一个名为getschema(MyCaseClass) 的函数,该函数将通过使用Encoders.product [MyCaseClass] .schema进行编码来返回我的架构,但Encoders.product并未将该案例类作为参数。
case class Moviedata(id:Int, name:String, year:Int, rating:Double,duration:Int)
//calling the function defined in another class
val movieSchema = getSchema(Moviedata)
//this is not working
def getSchema[T](t:Class[T])={
Encoders.product[t].schema
}
//this works when defined in the same class but how to generalize into a function
//val movieSchema = Encoders.product[Moviedata].schema
Here is the working example, don't forget about the import 这是工作示例,请不要忘记导入
import scala.reflect.runtime.universe._
case class Moviedata(id:Int, name:String, year:Int, rating:Double,duration:Int)
val movieSchema = getSchema(Moviedata)
def getSchema[T <: Product : TypeTag]={
Encoders.product[T].schema
}
Some explanations. 一些解释。
Encoders.product
takes type parameter
not a class and doesn't have arguments. Encoders.product
采用type parameter
而不是类,并且没有参数。
def getSchema[T]={
Encoders.product[T].schema
}
Unfortunately, it is still not enough for the compiler, it needs to know the runtime type of your instance. 不幸的是,对于编译器来说这还不够,它需要知道实例的运行时类型。 Scala's way to provide it is via TypeTag
trait that is added as an implicit parameter. Scala提供它的方式是通过TypeTag
特征添加为隐式参数。
def getSchema[T](implicit t : TypeTag[T])={
Encoders.product[T].schema
}
Or in a more concise way: 或者以更简洁的方式:
def getSchema[T : TypeTag]={
Encoders.product[T].schema
}
But there is another restriction, your class must also be a Product
但是还有另一个限制,您的课程也必须是Product
def getSchema[T <: Product : TypeTag]={
Encoders.product[T].schema
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.