为了便于在Scala中使用Avro,我想基于存储在.avro文件中的模式来定义案例类.我可以尝试:
谢谢,任何建议表示赞赏.-Julian
我想回答这个问题.
而不是写:
case class Person(name: String, age: Int) {
def this() = this("",1)
}
Run Code Online (Sandbox Code Playgroud)
我以为我会使用宏注释来扩展它:
@Annotation
case class Person(name: String, age: Int)
Run Code Online (Sandbox Code Playgroud)
所以我尝试DefDef在宏注释的impl中使用quasiquotes 将新构造函数添加为普通的,如:
val newCtor = q"""def this() = this("", 1)"""
val newBody = body :+ newCtor
q"$mods class $name[..$tparams](..$first)(...$rest) extends ..$parents { $self => ..$newBody }"
Run Code Online (Sandbox Code Playgroud)
但是这会返回一个错误: called constructor's definition must precede calling constructor's definition
有办法解决这个问题吗?我错过了什么?
谢谢你看看,朱利安
当注释的参数是常量时,我获得了成功,例如:
@Annotation(2)
class AnnotatedClass
Run Code Online (Sandbox Code Playgroud)
因为我可以通过以下方式获取宏中的值impl:
c.prefix.tree match {
case Apply(_, List(Literal(Constant(x)))) => x.toInt
}
Run Code Online (Sandbox Code Playgroud)
但是当注释的参数不是常数时,我很难过,比如:
object Obj {val n = 2}
@Annotation(Obj.n)
class AnnotatedClass
Run Code Online (Sandbox Code Playgroud)
在假开始类似这样的问题,我可以匹配c.prefix.tree一次拉出名称Obj和n,但我如何获得的价值Obj.n?