0

我正在查看一个提供类的隐式实现的 Scala 宏。此类将字段值映射转换为案例类。宏可以在这里找到,是它背后的解释。

目前,该实现忽略了输入映射中提供的冗余字段。我想添加一个类似于fromMap如果输入映射具有冗余条目时会引发异常的方法,但我不确定我是否理解得足够好。

我的理解是toMapParamsandfromMapParams是接受输入并对其应用Map或应用 Companion 对象的 Apply 方法的表达式。

因此,fromMapParams应该修改以将冗余值输出为字符串列表,格式如下:

case class CaseClassRedundantFieldException[T]
(redundantFields: List[String], cause: Throwable = None.orNull)
(implicit c: ClassTag[T])
extends Exception(s"Conversion between map of data-fields to ${c.runtimeClass.asInstanceOf[T]} failed" 
+ "as redundant fields were provided: $redundantFields",
    cause)

我想我需要简单地拥有类似的东西:

def fromMap(map: Map[String, Any]): $tpe = {
val redundant vals: fields diff $map 
if(vals.size > 0){ CaseClassRedundantFieldException(vals) } //(these two lines don't have the right syntax.)
$companion(..$fromMapParams )

}

我怎样才能做到这一点?

4

1 回答 1

1

不幸的是,您没有提供您现在拥有的最小、完整和可验证的示例,所以我不得不回到您开始的内容。我认为这个修改后的宏与您想要的非常相似:

def materializeMappableImpl[T: c.WeakTypeTag](c: Context): c.Expr[Mappable[T]] = {
  import c.universe._
  val tpe = weakTypeOf[T]
  val className = tpe.typeSymbol.name.toString
  val companion = tpe.typeSymbol.companion

  val fields = tpe.decls.collectFirst {
    case m: MethodSymbol if m.isPrimaryConstructor ⇒ m
  }.get.paramLists.head

  val (toMapParams, fromMapParams, fromMapParamsList) = fields.map { field ⇒
    val name = field.name.toTermName
    val decoded = name.decodedName.toString
    val returnType = tpe.decl(name).typeSignature

    (q"$decoded → t.$name", q"map($decoded).asInstanceOf[$returnType]", decoded)
  }.unzip3

  c.Expr[Mappable[T]] {
    q"""
    new Mappable[$tpe] {
      private val fieldNames = scala.collection.immutable.Set[String](..$fromMapParamsList)
      def toMap(t: $tpe): Map[String, Any] = Map(..$toMapParams)
      def fromMap(map: Map[String, Any]): $tpe = {
        val redundant = map.keys.filter(k => !fieldNames.contains(k))
        if(!redundant.isEmpty) throw new IllegalArgumentException("Conversion between map of data-fields to " + $className + " failed because there are redundant fields: " + redundant.mkString("'","', ","'"))
        $companion(..$fromMapParams)
      }
    }
  """
  }
}
于 2018-01-25T16:12:25.347 回答