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. In this post, I will give some basic information on Vert.x as a tool set for writing reactive applications on the JVM and also introduce Kotlin a bit. In the end, I want to demonstrate how this application can be set up in Gradle.
Vert.x - Reactive Programming tool-kit
Vert.x is 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 the development of reactive software quite easily.
It is also modular, very fast and yet lightweight (~650kB) and altogether provides a reasonable alternative to other, maybe better known, microservice frameworks.
Kotlin
Kotlin is a pretty new open-source JVM language that is sponsored by the great guys of JetBrains, currently available in Version 1.1.50. Its types are static and Kotlin is fully interoperable with Java. JetBrains' idea in creating this language was to find a more productive alternative to Java, still being compatible with 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, Scala and many more modern language trying to combine the advantages of all of them.
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!
It’s time to show some language features of Kotlin in action:
Local Variable Type Inference
The following lines of code demonstrate how you define variables 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. This works in most cases but, of course, it's also possible to declare the variable type explicitly as in var myvar3: Double = 1.0
.
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
We all know what NullpointerException
s are - we all hate them. Kotlin tries to eliminate these by distinguishing between nullable and not-null references. Guess, what's the 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 result in the String’s length if iCanBeNull
is not null
, and to null
otherwise. Trying to naively call iCanBeNull.length
will not compile.
String Templates
Another very useful feature that 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 for Kotlin Reactive Programming
In the following, you can see my Gradle file, which contains the following tasks:
- Kotlin compiles 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)
The Kotlin file "Starter.kt" contains the application's entry point: themain
method. The compiler generates a "StarterKt" class, which has to be the Main-Class.
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)
}
}
Afterward, you can build
and run
your application as shown here:
- ./gradlew build
- ./gradlew run
You can check out my sample code on GitHub, which includes some examples of HTTP routing using Vert.x web, also showing how to work with template engines. Have fun with Kotlin Reactive Programming.
Simon is a software engineer with 9+ years of experience developing software on multiple platforms including the JVM and Serverless environments. He currently builds scalable distributed services for a decision automation SaaS platform. Simon is a self-appointed Kotlin enthusiast.
[…] More features of Kotlin are described in my Post on Vert.x. […]
[…] For a more detailed introduction to Kotlin’s features you can have a look at my recent posts like this one. […]
[…] Non-blocking programming became more and more popular in the last time because reactive programming gained influence. 2. Actually it’s “possibly suspending” since such a function might […]
[…] which is a Kotlin web application based on the Vert.x toolkit. Learn more about the technology in this post I wrote […]
[…] taken from a sample vert.x application and defines a local function that is reused twice afterward. A great way to simplify […]
[…] RxJava, Vert.X or Akka for example. If you’ve never come across these, you can read my post on Kotlin with Vert.X as a first […]
[…] Scala feature JetBrains considered relevant and suitable for Kotlin? I like that Read this post if you’re interested in more Kotlin […]