隐式宏分辨率

时间:2015-07-29 23:49:31

标签: scala macros implicit-conversion implicit implicits

我试图获取由宏生成的隐式参数。当请求隐式的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]传递给隐式点中的函数,它可以正常工作。为什么我需要包装器,我可以摆脱它吗?

0 个答案:

没有答案