How are Scala traits compiled into Java bytecode?

前端 未结 4 2042
半阙折子戏
半阙折子戏 2020-11-30 00:33

I have played around with Scala for a while now, and I know that traits can act as the Scala equivalent of both interfaces and abstract classes. How exactly are traits comp

4条回答
  •  甜味超标
    2020-11-30 00:51

    In the context of Scala 12 and Java 8, you can see another explanation in commit 8020cd6:

    Better inliner support for 2.12 trait encoding

    Some changes to the trait encoding came late in the 2.12 cycle, and the inliner was not adapted to support it in the best possible way.

    In 2.12.0 concrete trait methods are encoded as

    interface T {
      default int m() { return 1 }
      static int m$(T $this) {  }
    }
    class C implements T {
      public int m() { return T.m$(this) }
    }
    

    If a trait method is selected for inlining, the 2.12.0 inliner would copy its body into the static super accessor T.m$, and from there into the mixin forwarder C.m.

    This commit special-cases the inliner:

    • We don't inline into static super accessors and mixin forwarders.
    • Instead, when inlining an invocation of a mixin forwarder, the inliner also follows through the two forwarders and inlines the trait method body.

提交回复
热议问题