2

我正在尝试获取由宏生成的隐式参数。隐式请求 StructTypeInfo 时,出现编译器错误,log-implicits 显示:

 [info] Test.scala:29: materializeCaseClassSchemaType is not a valid implicit value for org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo because:
 [info] hasMatchingSymbol reported error: We cannot enforce T is a case class, either it is not a case class or this macro call is possibly enclosed in a class.

我编译它的方法是,如果我将它包装在一个参数化的类中:

trait SchemaWrapper[T] {
  def schema: StructTypeInfo
}

这里有一些相关的代码(如果我遗漏了一些东西,请告诉我):

// Implicits, one works, one doesn't
object MacroImplicits {
  // Works:
  implicit def materializeCaseClassSchemaTypeWrapper[T]: SchemaWrapper[T] = macro SchemaTypeImpl.caseClassSchemaTypeWrapper[T]
  // Doesn't:
  implicit def materializeCaseClassSchemaType[T]: StructTypeInfo = macro SchemaTypeImpl.caseClassSchemaType[T]
}

// Implementation (most of it probably not relevant)
// Another version returns StructTypeInfo directly without the wrapper
object SchemaTypeImpl {
  def caseClassSchemaTypeWrapper[T](c: Context)(implicit T: c.WeakTypeTag[T]): c.Expr[SchemaWrapper[T]] = {
  import c.universe._

  if (!IsCaseClassImpl.isCaseClassType(c)(T.tpe))
    c.abort(c.enclosingPosition, s"""We cannot enforce ${T.tpe} is a case class, either it is not a case class or this macro call is possibly enclosed in a class.""")
    ...
  }
}

有趣的是,如果我materializeCaseClassSchemaType[MyCaseClass]在隐式位置显式传递给函数,它就可以正常工作。为什么我需要包装器,我可以摆脱它吗?

4

0 回答 0