简体   繁体   English

scala:如果实例类型是静态基类,则使用基于宏的扩展类的方法调用 trait default impl

[英]scala: using method of extending class based on macros invokes trait default impl if type of instance is statically the base class

I have a trait T, I implement it with macro in class C. i create an instance of C and invoke its methods.我有一个特征 T,我在类 C 中用宏实现它。我创建了一个 C 的实例并调用它的方法。 if the type of the val containing an instance of C is C - works as expected.如果包含 C 实例的 val 的类型是 C - 按预期工作。 if the type of the val containing an instance of C is T - invokes methods as if T.如果包含 C 实例的 val 的类型是 T - 就像 T 一样调用方法。

best way to describe it that i can come up with is "virtual table broken" in scala-macros, but i don't know if that's a thing...我能想到的最好的描述方法是 Scala 宏中的“虚拟表损坏”,但我不知道这是否是一回事......

example code:示例代码:

Type in expressions for evaluation. Or try :help.

scala>

scala>

scala> import language.experimental.macros
import language.experimental.macros

scala>

scala>

scala> trait T { def doSomething(): Unit = println ("trait") }
defined trait T

scala>

scala>

scala> import scala.reflect.macros.Context
import scala.reflect.macros.Context

scala>

scala>

scala> object Macro {
     |   def doSomething(c: Context)(): c.universe.Tree = {
     |     import c.universe._
     |     q"""println ("macro")"""
     |   }
     | }
warning: there was one deprecation warning (since 2.11.0); for details, enable `:setting -deprecation' or `:replay -deprecation'
defined object Macro

scala>

scala>

scala> class C extends T { override def doSomething(): Unit = macro Macro.doSomething }
defined class C

scala>

scala> val c: C = new C()
c: C = C@3bd1883a

scala> c.doSomething()
macro

scala>

scala> val t: T = new C()
t: T = C@4079fec7

scala> t.doSomething()
trait

Def macros are expanded at compile time so late binding / dynamic dispatch (which is a runtime feature) is impossible for them. def 宏在编译时被扩展,因此后期绑定/动态调度(这是一个运行时特性)对它们来说是不可能的。

At compile time it's unknown that t has type C , at compile time it's only known that t has type T .在编译时不知道t类型为C ,在编译时只知道t类型为T

See details here: Eugene Burmako.在此处查看详细信息:Eugene Burmako。 Unification of Compile-Time and Runtime Metaprogramming in Scalahttps://infoscience.epfl.ch/record/226166/files/EPFL_TH7159.pdf p. Scala 中编译时和运行时元编程的统一https://infoscience.epfl.ch/record/226166/files/EPFL_TH7159.pdf p。 98, §4.6.1 "Inheritance" 98, §4.6.1 “继承”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM