scala – 使用def宏实现抽象方法
发布时间:2020-12-16 09:49:12 所属栏目:安全 来源:网络整理
导读:似乎不可能通过def宏实现抽象方法: import scala.reflect.macros.Contextimport language.experimental.macrostrait A { def foo(): Unit}object AImpl { def fooImpl(c: Context)(): c.Expr[Unit] = { import c.universe._ c.Expr[Unit](reify().tree) }}t
似乎不可能通过def宏实现抽象方法:
import scala.reflect.macros.Context import language.experimental.macros trait A { def foo(): Unit } object AImpl { def fooImpl(c: Context)(): c.Expr[Unit] = { import c.universe._ c.Expr[Unit](reify().tree) } } trait AImpl extends A { def foo(): Unit = macro AImpl.fooImpl } 此操作失败,并显示以下错误: [error] .../A.scala:17: overriding method foo in trait A of type ()Unit; [error] macro method foo cannot override an abstract method [error] def foo(): Unit = macro AImpl.fooImpl [error] ^ 如果我删除扩展A它编译.但显然我希望AImpl满足特质A.如何解决这个问题? 另一个尝试: trait AImpl extends A { def foo(): Unit = bar() def bar(): Unit = macro AImpl.fooImpl } 给出了新的错误: [error] macro implementation not found: bar (the most common reason for that is that you cannot use macro implementations in the same compilation run that defines them) [error] one error found 解决方法
你确定你用先编译的宏和后来的AImpl进行了测试吗?
像第二次尝试一样使用转发器方法似乎有效(使用2.10.2): // first compilation run import scala.reflect.macros.Context import language.experimental.macros trait A { def foo(): Unit } object AImplMacros { def fooImpl(c: Context)(): c.Expr[Unit] = { import c.universe._ c.Expr[Unit](reify().tree) } } // second compilation run trait AImpl extends A { def foo(): Unit = bar() def bar(): Unit = macro AImplMacros.fooImpl } // compiles and runs: scala> val a = new AnyRef with AImpl a: AImpl = $anon$1@59225446 scala> a.foo scala> a.bar (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |