Introducing BeanPurée

Posted on April 5, 2017

As a Scala developer I prefer to use Scala libraries rather than Java ones for my code. However, it is not always possible. Sometimes I might not find a required library, or I just have to use some legacy code I already have. Even though Scala runs on a JVM and is fully compatible with Java, the languages have different ideologies, different code styles and sometimes different API’s. Thus, in Scala it is preferable to use immutable case classes for the data modeling. However, in Java the common building blocks are JavaBeans, which are mutable. Another problem is that a lot of Scala libraries expect case classes. Even if they work with JavaBeans, usually you have to write some boilerplate code.

So, quite often it is easier to have a separate model in your Scala code, and converters between Java model classes and Scala ones.

BeanPurée is a library that helps you to automate this process. And it helps you to do even more, because it’s a bridge from JavaBeans to shapeless.

Let’s take this Java class as an example:

BeanPurée provides BeanGeneric class, which has the same function with shapeless’s Generic:

We just get a BeanGeneric instance with representation type String :: Int :: Boolean :: HNil. Internally, BeanGeneric uses the getters order to build the Repr type. Let’s try to use it:

So far, so good, let’s combine it with shapeless:

Since the shape of Dog and ScalaDog is the same we can convert from one class to another using a combination of Generic and BeanGeneric.

Just as shapeless provides LabelledGeneric with field names information in the Repr type, BeanPurée provides LabelledBeanGeneric, which adds property names to the generic representation.

Having this stuff allows me to implement a more intelligent (but not too much) converter between case classes and beans. This class is called BeanConverter. It doesn’t rely on a definition order of properties . Instead, it uses names.

That’s all the features of the release 0.1, which is available in the Sonatype Maven repository. I have several ideas for the next releases, e.g automatic Java types to Scala types conversion, and partial converters.

Recent posts

Tag cloud

Akka BeanPurée DSL Gentoo Hakyll Haskell Java NVidia Scala Spray XMonad collections git sbt sbt-git-flow-version shapeless