Prototyping with Kotlin

Image by Ольга Бережна from Pixabay

Java is the King in the Enterprise world. Very often I need some quick prototyping interacting with some Java libraries. But Java is verbose and sometimes a lot of boilerplate codes can not be avoided. When a prototype is required, I often turn to some alternatives. I used to use Jruby, but nowadays I am exploring Kotlin as my 1st choice.

It's preferable and sometimes a must, that the developed prototype/tool has to be run on JVM, which is available for almost all of the different platforms in the enterprise world. Secondly, no installation should be required, therefore a flat jar (uber jar) which bundled all the dependencies together should be the end product.

Kotlin, 100% native java compatible is a good candidate for the above two requirements. Let’s explore some use cases.

Simple use case: Kotlin compiler

When we don’t need any java library, or the required Java module is included in one single jar file without any chained dependency, we can use the Kotlin compiler to package our prototype into a single jar file,

The option points to the destination jar file, while - make the jar as a flat jar where the Kotlin runtime is included, so it can run on any JVM as,

If the code is importing and calling some java library, say enterprise-lib.jar, then we can compile it by defining the classpath,

and later run it as,

Notice the main class’s naming convention.

Enterprise is complex, there might be a chain dependency of the libraries, we will need a tool to manage it.

Complex use case: Gradle based

Take the IBM MQ client as an example. As indicated in the maven repository, the MQ client library depends on many others. We don’t want to manually manage the dependency, we will leave it to Gradle.

Init a Gradle project by calling

Then interactively select the type of the project as application, Kotlin as the language, …, and define project name.

A scaffolding project is created. Now let's add the MQ dependency in the dependencies block,

In order to build the flat jar file, we use the shadow plugin, add it in the plugins part,

And define the main class for the jar file, by adding the following.

The main class is using the naming convention of ${package}.${Main.kt file name + “Kt”}

Code the MQ connection in Kotlin,

You may need to change the test source file, as we have removed the default class definition.

Now build the package,

The flat jar is then created as in

We are ready to test this prototype.