Generate a case class in scala

798 views Asked by At

How to generate case classes in scala based on information kept in 100s of java classes? Basically, I need this for writing a wrapper for a java library.

Is it even possible? I have a feeling that no. In that case what is the best alternative?

2

There are 2 answers

3
v6ak On

Of course you can. You can generate them before compilation. You will want to introspect the Java classes (maybe using the reflection API) and then generate corresponding Scala source code. You can either generate it once and copy to the repository or create a generator and use it in the building tool, e.g. in SBT.

You can generate the code either by hand (by concatenating the strings) or by a library like TreeHugger

0
Dmitriy Yefremov On

It is totally doable. Some ideas:

  1. It seems you do not need to generate code every time you compile your project. You can generate it once and either check-in into source control or publish as a library.
  2. Depending on whether you have access to the source code of the Java library or not you will need to use either .java parser or .class parser. Reflection may or may not work for you (the main constraint is you need to have the class in the classpath of the current JVM and load it in memory to access it via reflection API).
  3. For different approaches to Scala code generation with examples see this post.