基于Scala宏的注释重用
考虑基于Scala宏的注释,例如from。注释需要两个参数:最大缓存大小和生存时间,例如基于Scala宏的注释重用,scala,annotations,scala-macros,scala-macro-paradise,Scala,Annotations,Scala Macros,Scala Macro Paradise,考虑基于Scala宏的注释,例如from。注释需要两个参数:最大缓存大小和生存时间,例如 @memoize(maxSize = 20000, expiresAfter = 2 hours) 假设您想要创建一个@cacheall注释,该注释相当于@memoize(maxSize=Int.MaxValue,expiresAfter=100天),以便简化样板文件并具有单个参数化点 这种类型的重用有标准模式吗?显然, class cacheall extends memoize(Int.MaxValu
@memoize(maxSize = 20000, expiresAfter = 2 hours)
假设您想要创建一个@cacheall
注释,该注释相当于@memoize(maxSize=Int.MaxValue,expiresAfter=100天)
,以便简化样板文件并具有单个参数化点
这种类型的重用有标准模式吗?显然,
class cacheall extends memoize(Int.MaxValue, 100 days)
由于宏中存在编译时参数解析,因此无法工作。标准模式是将注释设置为宏注释,该宏注释将被展开,并使用必要的参数打开必要的注释
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
class cacheall extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro cacheallMacro.impl
}
object cacheallMacro {
def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
val memoize = q"""
new _root_.com.softwaremill.macmemo.memoize(
_root_.scala.Int.MaxValue, {
import _root_.scala.concurrent.duration._
100.days
})"""
annottees match {
case q"${mods: Modifiers} def $tname[..$tparams](...$paramss): $tpt = $expr" :: _ =>
q"${mods.mapAnnotations(memoize :: _)} def $tname[..$tparams](...$paramss): $tpt = $expr"
}
}
}