supernatural
supernatural

Reputation: 1197

How to pass a case class into a function parameter and get a schema accordingly?

the function which will return me the schemaI 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.

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 

Upvotes: 0

Views: 1001

Answers (1)

Gelerion
Gelerion

Reputation: 1724

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.

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.

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

def getSchema[T <: Product : TypeTag]={
  Encoders.product[T].schema
}

Upvotes: 1

Related Questions