How can I see in what [Java/Scala?] code does Scala compiler rewrites original Scala-code

大憨熊 提交于 2019-12-30 00:33:13

问题


Following Scala mailing lists, different people often say: "compiler rewrites this [scala] code into this [java/scala??] code". For example, from one of the latest threads, if Scala sees

class C(i: Int = 4) { ... }

then the compiler rewrites this as (effectively):

class C(i: Int) { ... }
object C {
  def init$default$1: Int = 4
}

How can I find out, what will be the compiler output for my code? Should I decompile the resulting bytecode for that?


回答1:


You can use "-print" as compiler option, and scalac will remove all Scala-specific features.

For example, here is the original code:

class Main
{
    def test (x: Any) = x match {
        case "Hello" => println ("Hello World")
        case e: String => println ("String")
        case i: Int => println ("Int")
        case _ => println ("Something else")
    }
}

And if you use "scalac -print" to compile it, you will get the following Scala code.

[[syntax trees at end of cleanup]]// Scala source: Test.scala
package <empty> {
  class Main extends java.lang.Object with ScalaObject {
    def test(x: java.lang.Object): Unit = {
      <synthetic> val temp1: java.lang.Object = x;
      if (temp1.==("Hello"))
        {
          scala.this.Predef.println("Hello World")
        }
      else
        if (temp1.$isInstanceOf[java.lang.String]())
          {
            scala.this.Predef.println("String")
          }
        else
          if (temp1.$isInstanceOf[Int]())
            {
              scala.this.Predef.println("Int")
            }
          else
            {
              scala.this.Predef.println("Something else")
            }
    };
    def this(): Main = {
      Main.super.this();
      ()
    }
  }
}



回答2:


One can look at the generated bytecode with

javap -c -private ClassNameWithoutDotClass


来源:https://stackoverflow.com/questions/3784926/how-can-i-see-in-what-java-scala-code-does-scala-compiler-rewrites-original-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!