Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于Scala宏的注释重用_Scala_Annotations_Scala Macros_Scala Macro Paradise - Fatal编程技术网

基于Scala宏的注释重用

基于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

考虑基于Scala宏的注释,例如from。注释需要两个参数:最大缓存大小和生存时间,例如

@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"
    }
  }
}