14.6. Disassembling and Decompiling Scala Code

Problem

In the process of learning Scala, or trying to understand a particular problem, you want to examine the bytecode the Scala compiler generates from your source code.

Solution

You can use several different approaches to see how your Scala source code is translated:

  • Use the javap command to disassemble a .class file to look at its signature.

  • Use scalac options to see how the compiler converts your Scala source code to Java code.

  • Use a decompiler to convert your class files back to Java source code.

All three solutions are shown here.

Using javap

Because your Scala source code files are compiled into regular Java class files, you can use the javap command to disassemble them. For example, assume that you’ve created a file named Person.scala that contains the following source code:

class Person (var name: String, var age: Int)

If you compile that file with scalac, you can disassemble the resulting class file into its signature using javap, like this:

$ javap Person
Compiled from "Person.scala"
public class Person extends java.lang.Object implements scala.ScalaObject{
  public java.lang.String name();
  public void name_$eq(java.lang.String);
  public int age();
  public void age_$eq(int);
  public Person(java.lang.String, int);
}

This shows the signature of the Person class, which is basically its public API, or interface. Even in a simple example like this you can see the Scala compiler doing its work for you, creating methods like name(), name_$eq, ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.