matanox
matanox

Reputation: 13716

obtaining the source of a case class's automatically generated methods

How can one obtain the code of all automatically generated methods of a case class, to cleanly preserve any of them when refactoring to a regular (non-case) class? is there some compilation flag that reveals the case class's auto-generated methods, or some other way, that ultimately reduce this to a cut & paste?

I have been under the impression that there are compilation flags to reveal automatically expanded definitions....

Upvotes: 0

Views: 180

Answers (2)

Chirlo
Chirlo

Reputation: 6132

You can see what the compiler desugars the source code to with the -Xprint:<phase> flags. For your example (seeing which code is generated for case classes), run:

scalac -Xprint:typer YourScala.sca

With -Xshow-phases flag you'll see all the available phases.

But the output you see is not compilable scala source code, but some intermediate representation.

Upvotes: 1

Stefan Sigurdsson
Stefan Sigurdsson

Reputation: 221

This is maybe not that easy.

The compiler generates byte code, so it isn't possible to copy compiler output and paste into source code.

You could read through the generated byte code and recreate Scala code for analogous methods by hand. This would be a bit laborious, but the methods are relatively simple and understanding byte code is A Good Thing.

If there is a usable Scala decompiler somewhere, then decompiling the compiled case class would reveal the code you want.

Given that the methods are dependent on the fields of the case class, they are not likely to be available in the compiler implementation as anything that could be copied and pasted.

Perhaps the best bet is to look at the language specification and implement the methods as described for case classes.

Upvotes: 0

Related Questions