1

Ok, I know about javap tool and already looked on decompiled java class files. However there are still some question about how scala traits implemented in java as I'm more .net developer.

trait A{
  def foo = "A"
}

trait B extends A{
  override def foo = "B"
  def bfoo = "bfoo"
}

trait C extends A{
  override def foo = "C"
  def cfoo = "cfoo"
}

class D extends A

val d = new D with B with C

The interesting thing here is that above d instance is realized in java as

D d = new D()
{
  public void bfoo()
  {
    B.class.bfoo(this);
  }

  public void cfoo()
  {
    C.class.cfoo(this);
  }

  public void foo()
  {
    C.class.foo(this);
  }
};

What is that construction,

... new D() { //definition of methods}?

I mean, is it somewhat like, definition of new methods inside instance initializer? I tried to do the same way for myself, and it is compiling, but I didn't find a way to access methods defined that way. I mean inside instance initializers?

UPDATE

Ok, here is complete example and what it decompiles to

object MainClass{
  def main(args:Array[String]){
    val d = new D with B with C
    println(d.bfoo)
    println(d.cfoo)
    println(d.foo)
  }
}

trait A{
  def foo = "A"
}

trait B extends A{
  override def foo = "B"
  def bfoo = "bfoo"
}

trait C extends A {
  override def foo = "C"
  def cfoo = "cfoo"
}

class D extends A

And decompilation of main method:

public void main(String[] args) {
    D d = new D() {
      public String bfoo() {
        return B.class.bfoo(this);
      }

      public String cfoo() {
        return C.class.cfoo(this);
      }

      public String foo() {
        return C.class.foo(this);
      }
    };
    Predef..MODULE$.println(((B)d).bfoo());
    Predef..MODULE$.println(((C)d).cfoo());
    Predef..MODULE$.println(((C)d).foo());
}

Look how it's accessing in-place defined methods through casting. Does it make sense? Cannot understand that part, because when I tried to do it myself, it threw an exception.

somyqk
  • 49
  • 3
  • For your info, apart from it being a duplicate: Other JVM-languages are not implemented in Java, they are implemented in JVM bytecode. – skiwi May 20 '14 at 11:19
  • Isn't it right that jvm bytecode can be decompiled to java? That's how it decompiles to java. – somyqk May 20 '14 at 11:24
  • Note also, that [question on such usage of new keyword was asked just today](http://stackoverflow.com/q/23754494/298389). – om-nom-nom May 20 '14 at 11:47

0 Answers0