Codementor Events

Three years with Kotlin: what they taught me.

Published May 04, 2018
Three years with Kotlin: what they taught me.

Also “How I learned a better Java without touching Java”.

Originally published on blog.kotlin-academy.com by Alex Facciorusso

I don’t want to write an article just about Kotlin and how much is beautiful and how much I would like to have a “K” statue that waits me on the door like the Stormtrooper in the Barney Stinson’s home. That things are for fanatic people (I’m putting aside some money to buy the statue).

Instead, I will talk about code styles and concepts that Kotlin, like in a Miyagi “wax on wax off” training, taught me to follow also in Java legacy code.

Goodbye null-pointer exceptions! (And why you should not avoid lint.)

https://www.youtube.com/watch?v=bLHL75H_VEM

One of the features that made me fall in love with Kotlin was the nullability management.
This esoteric term practically says: “I can manage nulls better than you” — looking at Java with superiority.

Let’s admit: who didn’t ever faced a null-pointer exception?
With Kotlin you have the power to avoid null checking (actually not “avoiding” totally, but delegating it to the JVM).

// a is a variable that could be null. In Java, we have to make
// this:
if (a != null) {
    a.someMethod()
}

// In Kotlin we can do simply:
a?.someMethod()

It’s a quite nice feature, because in Kotlin you could have nullable variables and non-nullable ones.

After many years of Kotlin, I found myself , when programming in Java for legacy code, checking for nulls obsessively.
This obsession is a good one, ’cause it allows me to avoid and fix null-pointer exceptions before it appears.

About this, I have a suggestion for all developers, newbies and elder ones:

Please, DON’T IGNORE lint warnings.

Lint warnings are a good way to discover possible bugs, and also if some times they seem too pedantic, many times they’re right.

In Java we haven’t got a good null-pointers handling, but we could — and should! — use @NotNull (or @NonNull ) and @Nullable annotations to enforce generation of lint warnings (and to eliminate unwanted ones).

Embrace immutability

Explaining what is immutability is something outside of the scope of this post (but you can find it on Wikipedia); but I can say briefly that when an instance of a class can’t change values inside it, it’s considered immutable.

Immutability in Kotlin is quite straightforward: just use class or (better)data class specifying all your fields inside the main constructor with val instead of var.

But what about changing values if I have no setters?
If we are using data class, Kotlin generates sugar code for us, creating a copy method that allows us also to specify each field to be changed. For a normal class object, you have to create a similar method by yourself.

data class User(val username: String, val email: String, val )

val user = User("myuser", "myuser@example.com")
val userWithDifferentEmail = user.copy(email = "myuser@test.com")

In Java you can achieve the same result settings all class fields as final and creating a constructor that initialises all those variables. And you could also take advantage of the builder pattern.

Is always a good idea to use immutability?
Well, immutability has only one disadvantage: for editing an object, you have to create a new copy of that. And instantiating objects have a cost.

But if your models are not too sophisticated — and in the 99% of cases they are not — , go with immutable models, because every bug you can ward off using this paradigm is worth the extra work for using it: every possible bug is very expensive for a developer (and for the company he works for).

Final (read-only or immutable) variables

On the same rail of immutable classes, we have to talk about variables defined as val in Kotlin, or final in Java.

// a read-only variable in Java...
final String hello = "Hello!";

// ...and this is the same code in lovable Kotlin <3
val hello = "Hello!"

In the previous code you can be sure , also without a documentation that says it explicitly, that the variable hello won’t change in the course of the code.

Using final variables can avoid introducing some annoying bugs, and makes code more readable and self-documented. We are humans, and as humans we need some restrictions to be sure to not make errors; and also if the newest Java compilers are very smart, I like to think that specifying final keywords will help to optimise the generated bytecode (I know, I’m a romantic guy).

“But Alex, when should I use final variables?”
I think that the most sensible question to ask is: “When should I use non- final variables?”.
The answer is: if you need to change, at some point of the code, the value of that variable, then go with mutable variables. In all other cases, use final variables.

Kotlin is a very good programming language, that can help us become better programmers. If you program in Java and you have not yet tried it, do it. Trust me.

I hope that you liked this article. If yes, press the 👏🏻 button as many times you want : for you they are just clicks, but means a lot for me (see also dopamine release).

P.S. don’t steal the soviet-propaganda poster on the head of the article, or at least ask for it 😁.


If you like it, remember to clap. Note that if you hold the clap button, you can leave more claps!

To be up-to-date with great news on Kotlin Academy, subscribe to the newsletter and observe Twitter.

Discover and read more posts from Kotlin Academy
get started
post commentsBe the first to share your opinion
Show more replies