Setup Vert.x Application written in Kotlin (Gradle Build)

Setup Vert.x Application written in Kotlin (Gradle Build)

I decided to write a Vert.x application in combination with Kotlin in a simple example because I’m really interested in Reactive Programming and love to use Kotlin. This post will give some basic information on Vert.x as a tool set for writing reactive applications on the JVM as well as a few words on Kotlin. In the end, I want to demonstrate how this application can be set up in Gradle. Of course, this will be just one out of a million possible solutions…​

Vert.x

Vert.x is described as a “tool-kit” rather than a framework for writing reactive apps on the Java Virtual Machine. As defined in the “Reactive Manifesto” (published on September 16, 2014) “Reactive Programming” is some kind of architectural software pattern, which tries to solve today’s requirements on modern software applications. More precisely, reactive applications are expected to be “more flexible, loosely-coupled and scalable”, “easier to develop”, and finally “highly responsible“, which indeed sounds desirable, doesn’t it?

As one important implication, these applications need to be message-driven, which means applications only communicate via asynchronous, non-blocking messages. Vert.x in particular applies to the Manifesto and provides a great tool set that allows us to develop reactive software quite easily.

One important thing to mention: Vert.x is “polyglot”, i.e. it can be used with multiple languages including Java, JavaScript, Groovy, Scala, Ruby and (lucky me) Kotlin ♥.

It is also modular, very fast and yet very lightweight (~650kB). Altogether it provides a reasonable alternative to other, maybe better known, microservice frameworks.

Kotlin

Kotlin is a pretty new JVM language developed by the great guys of JetBrains, currently available in Version 1.1.50. It is statically typed and fully interoperable with Java. JetBrains’ idea in creating this language was to find a more productive alternative to Java, still being compatible to it. I think every Java developer who has been working with e.g. Groovy or Scala knows that Java requires a lot of boilerplate code for some simple tasks and has quite a few flaws. Kotlin is inspired by Java and Scala trying to combine the advantages of both.

Just a few days ago, Google announced Kotlin to be an official Android programming language on this year’s Google I/O conference. I think this is the greatest achievement for Kotlin so far and I’d like to congratulate JetBrains for this milestone!

I think it’s time to give some examples of features available in Kotlin:

Local Variable Type Inference

The following lines of code demonstrate how variables are defined in Kotlin:

var myvar1 = 100
var myvar2 = "text"

The types of myvar1 and myvar2 (Int and String), are being inferred behind the scenes for us.

Data classes

Just think of a Java class Person, having attributes like name, age, job. The class is supposed to override Object ‘s toString(), hashCode() & equals() methods and of course provide getters and setters for each attribute.

data class Person(val name: String, val age: Int, val job: String)

That’s all you need to write in Kotlin – a real time saver.

Null Safety

Well…​ We all know what a NullpointerException is – we all hate it. Kotlin tries to eliminate it by distinguishing between nullable and not-null references. Guess, what kind is used by default? Absolutely, the non-null reference type, i.e. a variable of type String cannot point to null.
Just for the records, the corresponding nullable type would be String?.

This alone would not make a big difference, so using nullable types requires us to handle all NPE-prone cases like we can see here:

val iCanBeNull:String? = null;
//do some hard work with the string
iCanBeNull?.length

Line 3 will evaluate to the String’s length if iCanBeNull is not null, and to null otherwise. Trying to call iCanBeNull.length will not compile.

String Templates

Another very useful feature anybody will easily understand:

var insertMe = "Reader"
//Prints >>Hello Reader<< on Console
println("Hello $insertMe") 
More

The examples shown above are just a tiny, little set of features I really love about Kotlin and wished to find in Java as well. I’ve been working with Kotlin for a few months now and became a huge fan. I think in the beginning, it can take some time to get comfortable with the Java-unlike syntax, but soon you’ll experience many things, you’ll actually love and do not want to miss anymore…​

By the way: Some of the above mentioned language features are also traceable in the long list of “JDK Enhancement Proposals” (JPE), e.g. JEP 286: Local-Variable Type Inference, authored by Brian Goetz.

Let’s finally do something! – The setup

In the following you can see my Gradle file. What actually happens is:

  • Kotlin is configured to compile for Java 1.8 (we do not need 1.6 support here).
  • Dependencies are added for Vert.x, Kotlin, Logging & Testing
  • We use the application plugin for building an executable JAR (Main-Class is added to Manifest)
My Kotlin file “Starter.kt” contains the application entry point: the main method. It is being compiled to “StarterKt” and so this has to be my Main-Class.
build.gradle
import org.gradle.jvm.tasks.Jar
import org.jetbrains.kotlin.gradle.tasks.*

val kotlin_version = "1.1.50"
val vertx_version = "3.4.2"

plugins {
    application
    eclipse

    kotlin("jvm")
}

tasks.withType {
    kotlinOptions.jvmTarget = "1.8"
}

application {
    mainClassName = "de.swirtz.vertx.standalone.webserver.StarterKt"
    applicationName = "kotlinwithvertx"
    version = "1.0-SNAPSHOT"
    group = "example"
}


dependencies {
    compile(kotlin("stdlib", kotlin_version))
    compile(kotlin("reflect", kotlin_version))

    with("io.vertx:vertx") {
        compile("$this-core:$vertx_version")
        compile("$this-web:$vertx_version")
        compile("$this-web-templ-thymeleaf:$vertx_version")
    }

    compile("org.slf4j:slf4j-api:1.7.14")
    compile("ch.qos.logback:logback-classic:1.1.3")

    testCompile(kotlin("test-junit", kotlin_version))
    testCompile("junit:junit:4.11")
    testCompile("io.vertx:vertx-unit:$vertx_version")
}

repositories {
    mavenCentral()
    jcenter()
}

val fatJar = task("fatJar", type = Jar::class) {
    baseName = application.applicationName
    manifest {
        attributes["Main-Class"] = application.mainClassName
    }
    from(configurations.runtime.map {
        if (it.isDirectory) it else zipTree(it)
    })
    with(tasks["jar"] as CopySpec)
}

tasks {
    "build" {
        dependsOn(fatJar)
    }
}

Afterwards you can build and run your application. In my example I wrapped Gradle and therefore the calls look like this:

  1. ./gradlew build
  2. ./gradlew run

You can check out my sample code on GitHub. It includes some examples on HTTP routing using Vert.x web, also showing how to work with template engines.

Have fun and good luck,
Simon


 

Please follow and like me 🙂

8 Replies to “Setup Vert.x Application written in Kotlin (Gradle Build)”

Leave a Reply

Enjoy this blog? Please spread the word :)