{{announcement.body}}
{{announcement.title}}

Common Java patterns in Kotlin

DZone 's Guide to

Common Java patterns in Kotlin

I wrote this article with the idea that this is what I would’ve wanted when starting with Kotlin, and I plan on updating it as I learn more techniques.

· Java Zone ·
Free Resource

Recently, I’ve been using Kotlin for a project at work. As someone coming from a Java background, I’ve been taking notes on certain patterns that are used in Java, that can be done nicer in Kotlin. I feel like when using a new language, it’s easy to fall into the trap of writing non-idiomatic code simply because it’s what I would’ve done in another language.

I wrote this article with the idea that this is what I would’ve wanted when starting with Kotlin, and I plan on updating it as I learn more techniques. Anyway, let’s begin!

Multi-line Strings

Sometimes, it is nice to embed SQL or have HTML snippets in our application. In these cases, we want to be able to have a String that spans multiple lines. If we had it on a single line, it would be near impossible to read!

Java

In Java 11 and below, we have to resort to simple String + concatenation. Make sure you don’t forget to add new line endings \n or else when the String is built, it will all end up on one line!

Java
 




x


 
1
// Java 11 and older
2
String query = "SELECT w.id, w.title, w.date, we.weight, e.name\n" +
3
        "FROM workouts as w\n" +
4
        "LEFT JOIN workout_exercises as we ON w.id = we.workout_id\n" +
5
        "LEFT JOIN exercises as e on we.exercise_id = e.id\n" +
6
        "WHERE w.user_id = ?";



However, starting from Java 13, we have a much nicer way of writing this!

Java


This is an example of a Text Block, which is a preview feature in Java 13 and 14. At the time of writing, this feature will be finalized in Java 15.

Kotlin

For Kotlin, the syntax is similar to what is available in Java 13+.

Kotlin


You might be asking why we have to call the trimIndent function at the end. This is because if we don’t, Kotlin will construct the String including the initial whitespace indentation on each line. As we are only inserting that indentation for readability purposes, we have to call trimIndent which will remove this initial whitespace from each line.

I think this is a case where the Java way of Text Blocks is a bit better, as it will automatically trim the whitespace for us. However, Kotlin is here now and (at the time of writing) Java 15 is still a month or so away!

String Concatenation

Another common thing we like to do with Strings is to construct them with variables. For instance, we receive some input from the user and we want to create a message based on that input.

Java

Unfortunately, Java does not have a nice, modern way to do this and we have to resort to simply using + to build our String.

Java


We do have other options that are useful in certain situations, such as StringBuilder and String#format. But for simple, straight forward situations, we can only use +.

Kotlin

In Kotlin, we can use template expressions inside a String. This greatly improves readability when a String is concatenated with multiple values.

Kotlin

Static Utility Methods

When we want utility methods that we want to use without having create a new Object, it is common practice to add them as static methods on a class.

Frequently, ‘Util’ classes exist that only contain static methods. This is a pattern employed by popular libraries like Google Guava and Apache Commons.

Java

Java

Kotlin

In Kotlin, we have a few options.

Firstly, we can have a top-level function. That is, a function that is not attached to a class.  This language feature does not exist in Java.

We can call the function from anywhere we want, without needing to create a new object, or prefix a class name in front of the function call.

Kotlin
 




xxxxxxxxxx
1
10


 
1
// Using a top-level function
2
 
          
3
fun getLastLetter(str: String): Char {
4
    if (str.isEmpty()) {
5
        throw IllegalArgumentException("Provided string must not be empty")
6
    }
7
    return str[str.length - 1]
8
}
9
 
          
10
getLastLetter("abc") // => c



Next, we can add a method to an object. This is roughly equivalent to the static method way we saw in Java, and the calling code is the same.

Kotlin


Finally, we have an extension function. This is a cool feature that allows us to attach a method to an existing class, without the need of creating a subclass or a new wrapped type!

Kotlin


This extension function feature was one the initial features I saw when looking at Kotiln where I thought that it was really useful!

Singletons

In some cases, we want to be able to define and use singleton’s in our code.

Java

With Java, we can do this by creating a class with a private constructor. The class then provides a public static field that can be accessed from calling code.

Java

Kotlin

In Kotlin, we greatly reduce boilerplate code by simply defining a new object type.

Kotlin


For more information about object, please read the relevant docs.

Conclusion

I’ve covered how to write common Java techniques in idiomatic Kotlin. Often, the equivalent Kotlin code is shorter and more readable.

My advice for Java developers starting with Kotlin: always be learning! If you find yourself encountering a new problem in Kotlin and you solve it by writing Java-ish code, slow down and see if there’s a better way to do it in Kotlin. Have a search on Google or talk to your favourite coworker about it. This way, you will continuously learn best practices while still being productive!

Topics:
java, kotlin

Published at DZone with permission of Anthony Bruno . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}