如何使用 Symbol 或 Type 对象将泛型类型传递给泛型函数?

How to pass into generic type using a Symbol or Type object into a generic typed function?

在 Scala 中,是否可以将派生自 Symbol 或 Type 对象的类型传递给泛型函数?例如:

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]()

从上面的示例中,我有兴趣调用 a[Person]() 并在 a() 中使用反射从 Person 获取字段以使用每个字段的类型调用 b[?]()

is it possible to pass a type derived from a Symbol or Type object into a generic typed function?

方法 b 的类型参数 T 必须在编译时知道,但 x.typeSignature 只有在运行时才知道。

您可以尝试使用 compile-time reflection 而不是运行时。然后 x.typeSignature 在宏运行时已知,这是主代码的编译时间。

// macros subproject

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

def a[T](): Unit = macro aImpl[T]

def aImpl[T: c.WeakTypeTag](c: blackbox.Context)(): c.Tree = {
  import c.universe._
  val fields: Seq[Symbol] = weakTypeOf[T].members.filter(_.isMethod == false).toSeq
  val bCalls = fields.map(x => 
    q"b[${x.typeSignature}]()"
  )
  q"..$bCalls"
}

// main subproject

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

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

a[Person]()

// scalac: {
//  b[App.Address]();
//  b[Int]();
//  b[String]()
//}

类似的事情可以用Shapeless来完成。

import shapeless.ops.hlist.{FillWith, Mapper}
import shapeless.{Generic, HList, Poly0, Poly1}

def b[T](): Unit = println("b")

object bPoly extends Poly1 {
  implicit def cse[X]: Case.Aux[X, Unit] = at(_ => b[X]())
}

object nullPoly extends Poly0 {
  implicit def cse[X]: Case0[X] = at(null.asInstanceOf[X])
}

def a[T] = new PartiallyAppliedA[T]

class PartiallyAppliedA[T] {
  def apply[L <: HList]()(implicit
    generic: Generic.Aux[T, L],
    mapper: Mapper[bPoly.type, L],
    fillWith: FillWith[nullPoly.type, L]
  ): Unit = mapper(fillWith())
}

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

a[Person]()

//b
//b
//b

或者,如果您真的想使用运行时反射,则必须将 b[...]() 的编译推迟到运行时。您可以使用 toolbox.

import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox

val toolbox = currentMirror.mkToolBox()

def a[T: TypeTag](): Unit = {
  val fields: Seq[Symbol] = typeOf[T].members.filter(_.isMethod == false).toSeq
  val bCalls = fields.map(x => 
    q"b[${x.typeSignature}]()"
  )
  toolbox.eval(q"""
    import Obj._
    ..$bCalls
  """)
}

object Obj {
  def b[T](): Unit = println("b")
}

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

a[Person]()

//b
//b
//b