Kotlin, First Impressions: Exception Handling, If-Expression

Just recently my interest for Kotlin, JetBrains’ (the makers of the IntelliJ IDEA development environment) alternative to Java on the JVM, was piqued. These are the first things I’ve noticed.

Exception Handling

I’m not sure I’m liking this. Checked Exceptions aren’t checked any more, just as in Groovy (keep your fingers off of it) and, even worse, there’s no multi-catch in Kotlin. At least for now.

This means, instead of the following in Java…

try {
    Path path = Paths.get("F:\\Dxtory\\Mafia 2\\db.xml")
    Document document = builder.parse(path.toFile())
}
catch (IOException | SAXParseException) {
    println("Bam!")
}

… you write this in Kotlin (just like in Groovy btw.) – if you remember to handle exceptions. Not that the IDE tells you to.

try {
    val path = Paths.get("F:\\Dxtory\\Mafia 2\\db.xml")
    val document = builder.parse(path.toFile())
}
catch (e: IOException) {
    println("Bam!")
}
catch (e: SAXParseException) {
    println("Bam! SAX")
}

If-Expression

There are actually more expressions like this, e.g. when and even try-catch. I’ll stick with if for now.

So, instead of this in Java…

Path dataDir ;
if (null == location) {
    String os = System.getProperty("os.name").toLowerCase();
    if (os.indexOf("win") >= 0) {
        String path = System.getenv("APPDATA");
        appDataLocation = Paths.get(path, "Typical Nerd", "WorkTracker");
    }
    else {
        // TODO Is this working on *nix?
        dataDir = Paths.get("~/", ".TypicalNerd", "WorkTracker");
    }
}
else {
    dataDir = location;
}

… you write this in Kotlin. Neat.

val dataDir = if (null == location) {
    val os = System.getProperty("os.name").toLowerCase()
    if (os.indexOf("win") >= 0) {
        val path = System.getenv("APPDATA")
        Paths.get(path, "Typical Nerd", "WorkTracker")
    }
    else {
        // TODO Is this working on *nix?
        Paths.get("~/", ".TypicalNerd", "WorkTracker")
    }
}
else {
    location
}

In the end it only comes down to saving one line. But, it highlights the intention much more clearly. The result of the if is to assign a value to dataDir. Or to return it. In that case you don’t write return in every branch. It’s clear from the beginning the the if is supposed to return. Because it’s in front of the if.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s