使用 Quotes 反射生成 ADT 编解码
解读
在国内一线互联网与大数据公司的 Scala 后端/平台面试中,“用宏(Quotes & Splices)在编译期自动生成 ADT 的 JSON 编解码” 是高频压轴题。
面试官想确认四点:
- 你是否真的写过 Scala 3 宏,而不是只会用 circe-derivation 等黑箱库;
- 能否在 编译期 递归遍历 ADT 的所有子类型,并生成零反射、零运行时损耗的代码;
- 对 Quotes、Expr、Type、Symbol、Flags、CaseDef、TypeTree 等核心 API 的掌握深度;
- 是否理解 类型级编程与 quoted pattern matching 的组合打法,以及宏的调试、错误定位、增量编译兼容性。
题目通常要求:
- 支持 sealed trait + case object/case class 的完整 ADT;
- 生成 Encoder[A]/Decoder[A](可简化为
a => Json、Json => Either[Err,A]); - 编译期报错信息友好,不支持的产品类型必须给出明确提示;
- 不能引入任何第三方依赖,纯 Scala 3 标准库宏实现;
- 生成的代码必须 无 asInstanceOf、无 mirrors、无 runtime reflection。
知识点
- Scala 3 宏入口:
inline def deriveEncoder[A]: Encoder[A] = ${ genEncoder[A] } - Quotes 核心对象:
q: Quotes—— 所有 AST 构造与解构的入口; - Expr[A] 与 Type[A]:分别代表“代码”与“类型标签”,用
Type.of[A]拿到TypeRepr; - Symbol & Flags:
sym.flags.is(Flags.Case)判断是否为 case 类;sym.children取 sealed trait 的直接子符号; - ADT 递归拆解:
- sealed trait → 遍历
TypeRepr.typeSymbol.children; - case object → 单例;
- case class → 遍历主构造器参数,按名字与类型生成
Json.Obj字段;
- sealed trait → 遍历
- quoted patterns:
case '{ type t; $x:t} =>提取内部类型; - 错误报告:
q.reflect.report.errorAndAbort("xxx", pos); - 增量编译与可移植性:避免
java.io.Serializable等 JVM 专有类型; - 性能:宏展开后必须是 纯代码块,无
Class.forName、无runtimeMirror; - 测试策略:
scala-cli+verify在编译期即跑通所有分支,国内面试官常要求现场跑通sbt Test/compile。
答案
import scala.quoted.*
// 极简 JSON AST
enum Json:
case Null
case Bool(b: Boolean)
case Num(i: BigDecimal)
case Str(s: String)
case Arr(elements: List[Json])
case Obj(fields: Map[String, Json])
trait Encoder[A]:
def encode(a: A): Json
trait Decoder[A]:
def decode(j: Json): Either[String, A]
inline def deriveEncoder[A]: Encoder[A] = ${ genEncoder[A] }
inline def deriveDecoder[A]: Decoder[A] = ${ genDecoder[A] }
private def genEncoder[A: Type](using Quotes): Expr[Encoder[A]] =
import quotes.reflect.*
val tpe = TypeRepr.of[A]
val sym = tpe.typeSymbol
if !sym.flags.is(Flags.Sealed) then
report.errorAndAbort(s"${sym.fullName} 必须是 sealed trait 或 sealed abstract class")
def encodeCase(sym: Symbol): (String, Expr[Any] => Expr[Json]) =
val name = sym.name
val subTpe = sym.typeRef
val subExpr = '{ (x: Any) => x.asInstanceOf[AnyRef] } // 占位,后续替换
name -> { (x: Expr[Any]) =>
if sym.flags.is(Flags.Case) && sym.flags.is(Flags.Module) then
// case object
'{ Json.Obj(Map(${Expr(name)} -> Json.Str(${Expr(name)}))) }
else if sym.flags.is(Flags.Case) then
// case class
val fields = sym.primaryConstructor.paramSymss.headOption.getOrElse(Nil)
val fieldJsons = fields.map { f =>
val fieldName = f.name
val fieldTpe = f.tree match
case v: ValDef => v.tpt.tpe
case _ => report.errorAndAbort(s"无法提取字段类型 ${f.name}")
val select = Select(x.asTerm, f).asExpr
val fieldEncoder = Expr.summon[Encoder[fieldTpe.typeRef.type]].getOrElse {
report.errorAndAbort(s"找不到隐式 Encoder[${fieldTpe.typeRef.type}]")
}
'{ ${Expr(fieldName)} -> $fieldEncoder.encode($select) }
}
'{ Json.Obj(Map(${Expr(name)} -> Json.Obj(Map.from(${Expr.ofList(fieldJsons)})))) }
else
report.errorAndabort(s"子类型 ${sym.fullName} 必须是 case object 或 case class")
}
val cases = sym.children.map(encodeCase)
val body = '{
new Encoder[A]:
def encode(a: A): Json =
${
val scrutinee = '{a}.asTerm
val matches = cases.map { (label, gen) =>
val pat = Typed(Wildcard(), TypeTree.of(using Type.typeNameOf(label)))
CaseDef(pat, None, gen('{a}).asTerm)
}
Match(scrutinee, matches).asExprOf[Json]
}
}
body
private def genDecoder[A: Type](using Quotes): Expr[Decoder[A]] =
import quotes.reflect.*
val tpe = TypeRepr.of[A]
val sym = tpe.typeSymbol
if !sym.flags.is(Flags.Sealed) then
report.errorAndAbort(s"${sym.fullName} 必须是 sealed trait")
def decodeCase(sym: Symbol): (String, Expr[Json] => Expr[Either[String, A]]) =
val name = sym.name
name -> { (j: Expr[Json]) =>
if sym.flags.is(Flags.Case) && sym.flags.is(Flags.Module) then
'{ Right(${Ref(sym.companionModule).asExprOf[A]}) }
else if sym.flags.is(Flags.Case) then
val mod = sym.companionModule
val fields = sym.primaryConstructor.paramSymss.headOption.getOrElse(Nil)
val fieldDecoders = fields.map { f =>
val fieldTpe = f.tree match
case v: ValDef => v.tpt.tpe
case _ => report.errorAndAbort(s"无法提取字段类型 ${f.name}")
Expr.summon[Decoder[fieldTpe.typeRef.type]].getOrElse {
report.errorAndAbort(s"找不到隐式 Decoder[${fieldTpe.typeRef.type}]")
}
}
val fieldNames = fields.map(_.name)
val result = fieldNames.zip(fieldDecoders).foldLeft('{ Right(Map.empty[String, Json]) }) {
case (acc, (fname, dec)) =>
'{
$acc.flatMap { m =>
m.get(${Expr(fname)}) match
case None => Left(s"缺少字段 ${${Expr(fname)}}")
case Some(v) => $dec.decode(v).map(x => m - ${Expr(fname)})
}
}
}
'{
$j match
case Json.Obj(fields) =>
fields.get(${Expr(name)}) match
case None => Left(s"缺少分支标签 ${${Expr(name)}}")
case Some(Json.Obj(inner)) =>
val start: Either[String, Map[String, Json]] = Right(inner)
${result}.map(_ => ${Apply(Ref(mod), Nil).asExprOf[A]})
case _ => Left("标签对应值必须是对象")
case _ => Left("期望 Json.Obj")
}
else
report.errorAndAbort(s"子类型 ${sym.fullName} 必须是 case object 或 case class")
}
val cases = sym.children.map(decodeCase)
'{
new Decoder[A]:
def decode(j: Json): Either[String, A] =
${
val scrutinee = '{j}.asTerm
val matches = cases.map { (label, gen) =>
val pat = Literal(StringConstant(label))
CaseDef(pat, None, gen('{j}).asTerm)
}
val default = CaseDef(Wildcard(), None, '{Left("未知分支")}.asTerm)
Match(Select('{j}.asTerm, "obj"), matches :+ default).asExprOf[Either[String, A]]
}
}
使用示例
sealed trait Cmd
case class Login(user: String, pwd: String) extends Cmd
case object Logout extends Cmd
given Encoder[Cmd] = deriveEncoder[Cmd]
given Decoder[Cmd] = deriveDecoder[Cmd]
@main def test =
val cmd: Cmd = Login("kim", "123")
val json = summon[Encoder[Cmd]].encode(cmd)
println(json) // Obj(Map(Login -> Obj(Map(user -> Str(kim), pwd -> Str(123)))))
println(summon[Decoder[Cmd]].decode(json)) // Right(Login(kim,123))
现场演示技巧
- 用
sbt "~ Test/compile"实时看宏展开,面试官最爱看show输出; - 在
project/plugins.sbt打开-Xcheck-macros,主动暴露宏边界错误,体现工程素养。
拓展思考
- 性能极限:宏展开后能否生成 位级标签(tagged union)而非字符串,减少序列化体积?
- 互操作:国内微服务场景需与 Java 枚举、Jackson、Fastjson 共存,能否在宏里同时生成
@JsonTypeInfo注解? - 增量编译:当 ADT 跨模块时,宏依赖的 Symbol 可能处于未编译状态,如何用
Quotes.reflect.Symbol.isDefinedInCurrentRun做惰性降级? - 错误叠加:业务要求 字段级路径回传(如
user.name缺失),需在Decoder里引入Path累加器,利用宏在编译期把路径字面量拼接成字符串常量; - 法律合规:国内金融公司要求 脱敏日志,能否在宏阶段识别字段名带
*pwd*、*idNo*等关键字,自动生成掩码 Encoder,实现“零成本合规”?