Tag: java

Kotlin Features I miss most in Java

Kotlin Features I miss most in Java

My Life as a Java Dev

Although I’m a big supporter of the Kotlin programming language, I still do a lot of Java programming on a daily basis for my employer. Since I’m aware of the great functionalities of Kotlin, I’m often struggling with Java as it has some “pitfalls”, requires additional boilerplate and misses many features.
In this post, I’d like to describe which Kotlin features I miss most when coding in Java.

new and Semicolon

Ever since I’m doing Kotlin, there are two things I always forget when coding in Java: the new keyword for constructor invocations and the annoying ; to complete statements. Kotlin doesn’t have new and even semicolons are optional. I really appreciate this decision because it reduces the “syntactic noise“.

Data classes

In Kotlin, data classes are used for simple data containers, representing JSON objects or returning compound objects from functions amongst other use cases. Of course, Java doesn’t support this special type of classes yet. As a result, I often have to implement my own data class, which means a lot of boilerplate in Java.

One special use case is compound objects returned from functions. For example, let’s imagine a function that needs to return two objects. In Kotlin we could use a data class, or simpler, a Pair directly. In Java, I tend to create a value object, which is a class with several final fields, each of which instantiated through the constructor. Similar to Kotlin, I don’t implement getters and setters, but use the class’s fields directly as public properties. Unfortunately, this is not what we learned as best practice and most Java code style checkers will complain about it. I do not see any encapsulation issues here and it’s the least verbose approach in Java. The following shows such a compound object, the inner class Multi. In Kotlin this would be a one-liner.

public class MultiReturn {

    public static void main(String[] args) {
        new MultiReturn().useMulti();
    }

    public void useMulti() {
        Multi multi = helper();
        System.out.println("Multi with " + multi.count + " and " + multi.name);
    }

    private Multi helper() {
        return new Multi(2, "test");
    }
    
    private static class Multi {
        private final int count;
        private final String name;

        public Multi(int count, String name) {
            this.count = count;
            this.name = name;
        }
    }
}

Local Functions

In many situations, we tend to create private methods that are only used inside another single method in order to make this one more readable. In Kotlin, we can use local functions, i.e. functions inside functions (inside functions…), which enables some kind of scope. For me, this is a much cleaner approach, because the function is only accessible inside the function that actually uses the local one. Let’s look at an example.


fun deployVerticles() {

    fun deploy(verticleClassName: String) {
        vertx.deployVerticle(verticleClassName, opt, { deploy ->
            LOG.info("$verticleClassName has been deployed? ${deploy.succeeded()}")
        })
    }

    deploy("ServiceVerticle")
    deploy("WebVerticle")
}

It’s taken from a sample vert.x application and defines a local function that is reused twice afterward. A great way to simplify your code.

Single Expression Functions

We can create single expression functions in Kotlin, i.e. functions without an actual body. Whenever a function contains only a single expression, it can be placed after a = sign following the function declaration:


fun trueOrFalse() = Random().nextBoolean()

In Java, on the other hand, we always have to use a function body enclosed in {}, which ranges over at least three lines. This is also “syntactic noise” I don’t want to see anymore. To be fair, Java 1.8 makes it possible to define lambdas which can also solve this, less readable though (Can also be applied to local functions):


public class SingleExpFun {

    private BooleanSupplier trueOrFalse = new Random()::nextBoolean;

    private boolean getNext(){
        return trueOrFalse.getAsBoolean();
    }
}

Default Parameters

One very annoying part of Java is the way methods have to be overloaded. Let’s see an example:

public class Overloade
    public static void main(String[] args) {
        Overloader o = new Overloader();
        o.testWithoutPrint(2);
        o.test(2);
    }

    public void test(int a, boolean printToConsole) {
        if (printToConsole) System.out.println("int a: " + a);
    }

    public void testWithoutPrint(int a) {
        test(a, false);
    }

    public void test(int a) {
        test(a, true);
    }

}

We can see a class with a method test(int, boolean) that is overloaded for the default case and also a convenience method is available. For more complex examples, it can lead to a lot of redundant code, which is simpler in Kotlin by using default parameters.


fun test(a: Int, printToConsole: Boolean = true) {
    if (printToConsole) println("int a: " + a)
}

fun testWithoutPrint(a: Int) = test(a, false)

fun main(args: Array) {
    testWithoutPrint(2)
    test(2)
}

Calling multiple methods on an object instance (with)

Obviously, Kotlin is more functional than Java. It makes use of higher-order functions in incredibly many situations and provides many standard library functions that can be used as such. One of my favorites is with, which I miss a lot whenever I can’t use Kotlin. The with function can be used to create scopes that actually increase the readability of code. It’s always useful when you sequentially call multiple functions on a single object.


class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}

with(Turtle()) {
    penDown()
    for(i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}

The great thing is the usage of lambdas with receiver, which you can read about in one of my other posts.

Null-Safety

Whenever I work with nullable types since the time I started with Kotlin, I actually miss the type system’s tools to prevent null-related errors. Kotlin did a very good job by distinguishing nullable types from not-nullable ones. If you strictly make use of these tools, there is no chance you’ll ever see a NullpointerException at runtime.

Lambdas and Collection Processing

Kotlin places a lot of value on its lambdas. As shown in the with example earlier, there’s special syntax available for lambdas that makes its usage even more powerful. I want to underline that the way functions and especially lambdas are treated in the language makes it dramatically superior to Java. Let’s see a simple example of Java’s Streams, which were introduced along with lambdas in Java 1.8:

List list = people.stream().map(Person::getName).collect(Collectors.toList());

It’s a rather simple example of a Stream that is used to get a list of names from a list of persons. Compared to what we did before 1.8, this is awesome. Still, it’s too noisy compared to a real functional approach as pursued by Kotlin:

val list = people.map { it.name }

Or yet another example, in which salaries of employees are summed up to a total amount:

int total = employees.stream()
                      .collect(Collectors.summingInt(Employee::getSalary)));

So much simpler in Kotlin:

val total = employees.sumBy { it.salary }

The Kotlin examples show how simple it can be. Java isn’t a functional language and has a hard time trying to adopt functional features like lambdas and streams as we can easily observe in the snippets. It really sucks to go back to Java, if you ever experienced the beauty of Kotlin. Have you ever tried to use Eclipse after being familiar with IntelliJ? You know what I mean then.

Wrap-up

In this short post, I presented you my top Kotlin features I always miss when coding in Java. It’s just a selection of things, which will hopefully find their way into the Java language soon. But to be honest, there’s no reason to always wait for Java, when there already is a much sweeter language available… I want to point out, that starting with Kotlin really made me a much better programmer because I began wondering about certain features in both languages and also try to find ways to use Kotlin-dedicated things in Java by finding workarounds like arranging my code differently.

I’d be interested in the features you like most, feel free to comment.
Also, if you like, have a look at my Twitter account and follow if you’re interested in more Kotlin stuff 🙂 Thanks a lot.

If you want to read more about Kotlin’s beautiful features I recommend the book Kotlin in Action and my other articles to you.

Please follow and like me 🙂
Creating your own DSL in Kotlin

Creating your own DSL in Kotlin

Motivation

If you’ve been following my recent posts about Kotlin, you’ve probably noticed me mentioning Domain Specific Languages (DSL) already. Kotlin as a programming language provides some powerful features that allow us to create those DSLs. One of these features, I also already introduced, is called Function Literals with Receiver, others are the invoke convention or infix notation.

In this post we’ll have a look at the concept of DSLs and certainly see how we can create one with Kotlin in a relatively simple example:
I’ve often been struggling with Java’s API for setting up SSL/TLS connections in scenarios where https communication is required for example. Just recently, I had to implement different kinds of these in one of our applications. Doing this, I once again felt like wanting to write a little library that can support me with that task, hiding away all the difficulties and of course the boilerplate.

Read More Read More

Please follow and like me 🙂
Kotlin Conventions – Operator Overloading

Kotlin Conventions – Operator Overloading

Operator Overloading and Conventions in Kotlin

Introduction

Kotlin supports a technique called conventions, everyone should be familiar with. For example, if you define a special method plus in your class, you can use the + operator by convention.
In this article I want to show you which conventions can be used and will provide some Kotlin code demonstrating the concepts of course.

Read More Read More

Please follow and like me 🙂
Kotlin on the JVM – Bytecode Generation

Kotlin on the JVM – Bytecode Generation

Kotlin on the JVM – How can it provide so many features?

Introduction

What exactly is a “JVM language”? Isn’t only Java meant to be run on the JVM?
Kotlin provides many features that aren’t available in Java such as a proper function type, extension functions or data classes. How was this even achievable? I’ve taken a deeper look at how Kotlin is made possible and what “JVM language” actually means. We’ll be having a look at Kotlin’s bytecode generation. I hope to help some people understanding a few things better 🙂

For a more detailed introduction to Kotlin’s features you can have a look at my recent posts like this one.

Please follow and like me 🙂
Sealed Classes in Kotlin – An Explanation

Sealed Classes in Kotlin – An Explanation

Sealed Classes in Kotlin – An Explanation

Today I came across Sealed Classes in Kotlin, which I had never heard of before. After some research I found that this concept is nothing new and is also available in Scala for example. So, yet another Scala feature JetBrains considered relevant and suitable for Kotlin? I like that 🙂 Read this post if you’re interested in more Kotlin features.

Actually this is a quite simple feature, which I’m going to explain in the following.

Feature Explanation

A sealed class can be subclassed and may include abstract methods which means sealed classes are abstract implicitly, although the documentation doesn’t clearly say so. To actually make a class “sealed” we have to put the sealed modifier before its name, as we can see here:

sealed class MyClass

Restriction

The important thing about sealed classes is that its subclasses must be declared in the same file as the sealed class itself.

Benefit

The feature allows us to define class hierarchies that are restricted in its’ types, i.e. subclasses. Since all subclasses need to be defined inside the file of the sealed class, there’s no chance of unknown subclasses which the compiler doesn’t know about.

Wait… Isn’t this what an enum actually is?

Kotlin’s sealed classes are some kind of extension of plain enums: As opposed to enums, subclasses of sealed classes can be instantiated multiple types and can actually contain state.

Use Case

The main advantage of sealed classes reveals itself if it’s used in when expressions. Let’s compare a normal class hierarchy to one of a sealed class handled in a when. First, we’ll create a hierarchy of Mammals and then put it in a method with a when:

open class Mammal(val name: String)
class Cat(val catName: String) : Mammal(catName)
class Human(val humanName: String, val job: String) : Mammal(humanName)
fun greetMammal(mammal: Mammal): String {
    when (mammal) {
        is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}"
        is Cat -> return "Hello ${mammal.name}"
        else -> return "Hello unknown"
    }
}

The else is mandatory, otherwise the compiler will complain. This is because it just cannot verify that all possible cases, i.e. subclasses, are covered here. It may be possible that a subclass Dog is available at any time which is unknown at compile time.

Sealed “to the rescue”

But what if we knew there wouldn’t be other Mammals in our application? We’d want to leave out that else.

The problem of unknown subclasses can be avoided by sealed classes. Let’s modify the base class Mammal, its’ subclasses can remain the same.

sealed class Mammal(val name: String)

Now we can simply omit the else clause since the compiler can verify that all possible cases are covered because only the subclasses in the file of the sealed class exist, without exception. The method now looks as follows:

fun greetMammal(mammal: Mammal): String {
    when (mammal) {
        is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}"
        is Cat -> return "Hello ${mammal.name}"
        // `else` clause not required, all the cases covered 
    }
}

That’s it. In conclusion really simple and handy, isn’t it? Have fun trying it yourself!

I’m going to create an example in KotlinByExample for this topic as soon as possible.

Finally, if you want to read about sealed classes in more detail I recommend the book Kotlin in Action to you!

Simon


 

Please follow and like me 🙂
Generic Types and Variance in Kotlin compared to Java

Generic Types and Variance in Kotlin compared to Java

Basics – What is Variance?

Many programming languages support the concept of subtyping, which allows us to implement hierarchies like “A Cat IS-An Animal“. In Java we can either use the extends keyword in order to change/expand behaviour of an existing class (inheritance) or use implements to provide implementations for an interface. According to Liskov’s substitution principle, every instance of a class A can be substituted by instances of its subtype B. The word variance, often referred to in mathematics as well, is used to describe how subtyping in complex aspects like method return types, type declarations, generic types or arrays relates to the direction of inheritance of the involved classes. There are three terms we need to take into account: Covariance, Contravariance and Invariance.

Read More Read More

Please follow and like me 🙂
Java Oracle Certification

Java Oracle Certification

Java Oracle Certification – Should you consider it?

I took the OCA SE 7 Programmer I Certification exam two years ago in 2015, which I passed successfully with a score of 86%. This year I will be taking the second exam of this certification path called OCP SE 7 Programmer II. In this post I want to reflect why taking these kind of exams isn’t a waste of time but can be a great advantage for you as a Java developer. Of course, being certified in whatever area will increase your chances of getting a better job because certificates represent some kind of guaranty of your skills to a company. No doubt about that.

Read More Read More

Please follow and like me 🙂

Enjoy this blog? Please spread the word :)