Kotlin: Let’s Kill the Dreaded Java Null Pointer Exception

I’ve been spending some time with Kotlin this weekend. While I’m still getting to know Kotlin myself, it seems like a language that’s worth your time as an enterprise developer, particularly if you’ve got a legacy enterprise Java code base that you can’t realistically migrate en masse. Helpfully, Kotlin can run side by side with that legacy code and buy you modern language features incrementally (more on this later).

nullpointerexceptionKotlin has many benefits — from cleaner, more succinct enterprise code to modern, functional capabilities (especially with funKTionale). In this post, I want to drill in on a mundane issue, an issue near and dear to many enterprise Java developers: solving the dreaded null pointer exception problem, a problem also known as the “billion dollar mistake.”

First of all, Kotlin takes an oblique approach to the null pointer problem: it simply doesn’t allow accidental null pointers. For example, you can’t do the following because you’ll get a compile error (try it yourself):

If you must have a variable that might be null, you need to demarcate it as optional with the following (clean, IMO) syntax:

Notice the question mark? As you might have guessed, it denotes a variable that could be null, which is similar to (but so much more succinct than) Optional in Java 8+ (or similar Guava features).

Given that syntax, the Kotlin compiler is able to provide you substantial null safety. In the following example, it is always going to be safe to ask for the length of the string in name because the variable name can never be null — ever.

However in the next example, if you try to compile code that checks the length of the name string in example 2 without checking for null first, you’ll get an error.

Let’s look at a somewhat more elaborate example:

In this example, we have two classes where the Address of a Person could be null. We also have some instances of people, one of which can never be null and one that can. Again you can see the compiler won’t let you directly access a nullable variable null without handling the possibility of the null (with the “?” syntax above).

The Kotlin compiler is smart about null safety in other ways too:

As you can see, in the first example, the compiler detects when you access the address field within a null check, which is a pattern familiar to Java developers (maybe painfully familiar?), and lets you proceed.

The second example is a little more interesting and succinct. It shows how you can use the Kotlin elvis operator to safely access a variable that could be null. The first part will print the postal code if it’s non-null and the second, optional, operator (?:) will respond with a different string when address is null — no if statements required!

Also interesting to note in the examples are the string templates, which we will discuss in another post.

Hello, world with Kotlin and Maven

Kotlin seems like an interesting language for Java enterprise developers who want to introduce a new simpler language with modern functional features but who can’t realistically leave their legacy Java code behind. Also, Kotlin is super easy to read, learn, and code — IMO, anyway.

I noticed a lot examples are based on Gradle. I think Gradle is great. But since most of the Java developers I work with are used to Maven and the project object model (“POM”), I thought this post might be somewhat useful for you. First, we need is a simple Maven POM:

Next, create a file named hello.kt in src/main/kotlin. Create a new source file named hello.kt (the name is important) and add this code:

You can see right away that Kotlin is different: the function is named differently, the arguments are defined differently, and there are no class references anywhere — even the function lives outside a class!

How to Run It

So that’s easy enough to get your Maven project set up for development. But what do you do with it? And how do you actually run it in the real world?

Inside the IDE

If you’re running in JetBrains’s IntelliJ, running it is as simple as clicking the Kotlin icon (among other methods):

Easy but obivously only useful if you’re code will never leave the IDE.

Assemble an Executable Kotlin Jar with Maven

To build a JAR that you can execute in a runtime environment, we’ll need to do some more work on your pom.xml file. In the build section, you need to add two additional plugins. First is the jar plugin:

This is a standard Maven plugin for adding a MANIFEST.mf file, which will tell the Java runtime which class to execute.

You might notice the mainClass element contains the cryptic looking word “HelloKt.” When you go a little further with Kotlin, you’ll learn that it’s completely interoperable with Java. When you want to call Kotlin code from Java, the Kotlin compiler names your classes with Kt suffix appended to the Kotlin source file name.

In our case we named our source file hello.kt, so Kotlin will expose our code to the Java world as HelloKt. You can override the naming with annotations, but I’ll save that for another post.

Now you can assemble an executable jar file. To run the file, however, you’ll need to put additional runtime Kotlin libraries on the classpath. So let’s build a fat jar with the runtime dependencies baked in by adding one more standard Maven plugin in our Maven build process:

Now drop into your command line, run mvn package on your project and you should be able to execute this command:

And Hello, world!

For More Information

JetBrains has a nice, succinct Maven guide for Kotlin with current version numbers. Also, this code is available on my Github account here: https://github.com/mrice/kotlin-maven-hello-world

kotlin_icon

Thanks to a comment from Eric for causing me to update the example with some guidance on how to actually run it!