jeudi 13 août 2020

In Scala, how to pass into generic type using a Symbol or Type object into a generic typed function?

In Scala, is it possible to pass a type derived from a Symbol or Type object into a generic typed function? For example:

case class Address(street: String, city: String, state: String, zipCode: String)
case class Person(name: String, age: Int, address: Address)

def a[T: TypeTag](): Unit = {
    val fields: Seq[Symbol] = typeOf[T].members.filter(_.isMethod == false).toSeq
    fields.foreach(x => {
       b[x.getMyType]() // How to pass field's "Type" into generic typed function?
    })
}

def b[T](): Unit = ???

a[Person]()

From the above example, I am interested in calling a[Person]() and within a(), use reflection to obtain the fields from Person to make calls into b[?]() using each field's type.





Aucun commentaire:

Enregistrer un commentaire