【问题标题】:Pass class type to a function in Scala将类类型传递给 Scala 中的函数
【发布时间】:2017-07-05 19:40:44
【问题描述】:

我有一个具有此签名的函数;

def process[E: TypeTag : ClassTag](id: Int): E = {

通常我会这样称呼它:

process[Item](1)

我需要从项目类型存储在变量中的地方调用它。

tt.tpe.members.collect {
  case m if m.isMethod && m.asMethod.isCaseAccessor => m.asMethod
} foreach { member => {
  // member is a MethodSymbol that can be used to get a type
  // how to call process[??](id) from here?

我假设我必须使用反射或返回类型,但我如何传递泛型类型?

【问题讨论】:

  • 为什么你认为member 是“一种类型”?这是MethodSymbol
  • 好的,谢谢!但我认为无论如何都有一种方法可以在这里使用它。我更新了问题。

标签: scala scala-reflect


【解决方案1】:

您可以将typeTagclassTag 显式传递给方法,它会从中推断出类型参数:

process(id)(typeTag, classTag)

要弄清楚如何从Type 获取TypeTag,请参阅here,要了解如何从TypeTag 获取ClassTag,请参阅here。 要从member 获取Type,请使用member.returnType

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2011-02-20
    相关资源
    最近更新 更多