That Missing Guide To Kotlin Part 2

Share if the site was helpful

That Missing Guide To Kotlin Part 2

In part one of our Kotlin series we began exploring the newly adopted language.  We saw a few examples of how it can make our code more concise and user friendly than Java including type inference and inline constructors.  In part two we’ll continue to show how Kotlin can make your code easier to work with while focusing on one dreaded Java roadblock: The NullPointerException.

If you’ve written anything in Java before then you’re familiar with NPE’s.  It occurs when you attempt to interact with a variable’s value, but it turns out there is no value to interact with.  Your compiler can’t see that there’s no value available, but at run-time your system checks for it and then crashes when it can’t be found.

Kotlin to the rescue

While Kotlin is 100% interoperable with Java (99% really as we’ll see soon) it’s fundamentally different in a few aspects.  One of these is nullability.  In Java every variable has a default value.  This is the value it can fall back on if you never explicity say what value it contained.  For example when you declare a boolean variable, unless you specify its value, it will be false.  For any variable that isn’t a primitive type, the default value will be null.  This can be really useful at times, but it allows us to accidentally try to grab a value when there isn’t one.

In Kotlin its possible to completely avoid this situation. Every variable that is declared is either a nullable type or a non-null type.  What this means is that along with declaring what type of value (Int, Boolean, custom class) your variable holds, you declare whether it is ever allowed to be null or not.  Here are two varaibles declared in Kotlin.  The first can never be null, while the second is nullable.

As you can see, the question mark is used to show a variable has the possibility of being null.  If there’s no question mark in the variables declaration, then you are safe to use it in every situation without risking it throwing an NPE.  This means that you’ll never have to write if statements checking if a variable is null to play things safe. Goodbye useless lines of code

Nullablility In Action

When using non-null type variables, we don’t have to check if there is a value present.  But for other situations we still must take precautions.  One way that Kotlin allows us to do this concisely is through safe calls.  A safe call looks similar to the traditional method of retrieving a value, except we include a question mark at the end of the variable.  So

Becomes

By doing this we can almost read the code as if it’s English.  We’re asking “does the pet exist?”, and if the answer to that question is yes then we move on to the name characteristic of our pet.  If there is no pet that has been created at this point in our code, instead of the app crashing our variable will be given a value of null.

This becomes incredibly powerful when we start chaining safe calls.  Let’s say we want to check if a company has an HR department with an employee name Toby who at tuna for lunch.  Instead of writing a null check for each of these before interacting with them we can write

If along the way any of these things doesn’t exist, then the code will finish the statement returning null and not interacting with any of the variables past the break.  Without an HR department the code won’t crash, but instead our employee variable will be set equal to null.

Control Is A Good Thing

This is probably the most common feature of Kotlin that you see people talk about, and it’s because of how powerful it is.  Not having to deal with null values is amazing, but even when we have to our code can be concise and clean.

The language can also smart cast nullable variables into non-null given the proper verification at first.  So if you had a nullable variable and then explicitly check if it wasn’t null, then you wouldn’t need to use any ?’s moving forward when accessing that variable.

Kotlin isn’t perfect, but when it comes to dealing with null values it has everything that Java has to offer with some additional perks and changes.  We’ll continue exploring some of Kotlin’s advantages in part 3.  In the mean time if you have any questions about how nullability works let us know in the comments below!

That Missing Guide To Kotlin

Share if the site was helpful

That Missing Guide To Kotlin

 

In 2017 Kotlin began taking the Android community by storm.  Google adopted it as a first class language, and shortly afterwards developers everywhere renounced Java in favor of the newer, sleeker language.  That change isn’t going away.

I won’t lie, when I first was exposed I didn’t see what all the fuss was about. There were tons of articles that talked about how revolutionary Kotlin was compared to Java, but other than avoiding NullPointerExceptions they didn’t seem to go in depth at all. Because of this all I saw was slightly different syntax.  Boy was I wrong.

Kotlin is not perfect, but it does have a lot to offer that you don’t really notice until you start writing code with it.  This is part 1 of a 3-part piece will dive deeper into some of the things Kotlin has to offer.  Ideally after reading these posts you’ll have a better idea of how Kotlin can make your codebase shorter, more efficient, and easier to read.

Let’s start with the basics

Before we get into anything fancy, let’s explore a very basic concept that Kotlin offers: type inference.  In Java when you’re declaring a variable you have to do two things.  First you have to say what type your value is going to be (String, int, byte, etc.).  Second you have to name your variable.  Additionally you can set the variable to a value, or if it’s a member variable you can let it default to null, 0, or false depending on its type.

Kotlin tries to alleviate this (even if it’s not that painful) with type inference.  The compiler is smart enough to know what kind of value you’re working with based on what you set it to. Instead of writing

You can write

var is the generic term for variable in Kotlin, and the compiler knows that we’re dealing with a String because the value “hello” is a string.  Ok, that’s really not very cool. But compare these three lines in Java and Kotlin:

A small difference, but once you start writing with it you’ll be surprised how nice it is to not have to give that split second to declaring the right type.  The var keyword will work for any type that we attempt to put in it, even customized classes.  The keyword val functions the same way except its value is final.  In fact, everything in Kotlin is declared final by default unless otherwise specified (more on that later).

Saving Space

Ok, so we can replace a type declaration with the words var or val.  That doesn’t really save us a ton of time or space in our code.  Let’s look at something a little more impressive: Constructors.

Let’s say the app your building has a database that you need to get into to provide users with information.  To manage this data you’ve built the class DataManager.  Here it is in Java:

And here it is in Kotlin.

What’s happening here?  Well we’re declaring the class the same way with the words “class DataManager”, but Kotlin allows for an inline constructor.  This means we can create our constructor inside of the class declaration by adding our parameters “variable1” and “varaible2”.  Notice that we had to declare the types of each of these two variables along with the word val.

But…Type Inference

This seems to go against what we just learned about type inference, but don’t worry its not.  Along with the type inference we’ve seen so far you can declare the type.  There are some situations where both are necessary/appropriate (such as an inline constructor).  What this code is doing is saying that our class will have two var’s that are Strings, but since we haven’t actually created an instance of the class yet there’s no way our compiler would be able to know the values are Strings unless we explicitly declare them to be.

By including val before each parameter we ask Kotlin to both use it as a constructor argument as well as declare it as a member variable for the class.  And Kotlin classes also take care of getters/setters for us automatically, so we don’t need to write those.

From 20 to 2

So by declaring my two member variables inline I’ve knocked my code down from 20 lines to 2.  Yes, 10 times less code.  Obviously not everything changes this drastically, but this is a great example of how Kotlin can both speed up your coding as well as make it neater.  And really by no means does the readability suffer here.  Reading this Kotlin code we can see clearly that DataManager takes 2 parameters in its constructor, and unless we specify otherwise, Kotlin will always take care of our getters and setters.

Again, this is just one instance where Kotlin saves code, but we could take this example even farther by overloading our constructor with default values.  That’s an example for another Kotlin post down the road, but hopefully even this one gives you a taste of how your codebase can shrink when you convert it.

If you want to go DEEP down the Kotlin rabbit hole, then Phonlab offers classes on it in the Android App Development course.  I’d highly recommend you check it out, as well as stay tuned for part #2 of this!