我正在查看一段Scala宏,它提供了一个类的隐式实现。此类将字段值映射转换为个案类。宏可以在这里找到,这是它背后的解释。
目前,实现忽略输入映射中提供的冗余字段。我想添加一个类似于fromMap
的方法,如果输入映射有冗余条目,它会引发异常,但我不确定我是否足够了解它。
我的理解是,toMapParams
和 fromMapParams
是接受输入并对其应用 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 )
}
我该怎么做?
不幸的是,您没有提供您现在拥有的最小、完整和可验证的示例,所以我不得不回到您开始的内容。我认为这个修改后的宏的作用与您想要的非常相似:
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)
}
}
"""
}
}