Null Safety in Kotlin

Peter Sommerhoff
A free video tutorial from Peter Sommerhoff
Developer & Software Engineer - With 45,000+ Happy Students
4.5 instructor rating • 6 courses • 62,508 students

Learn more from the full course

Kotlin for Android & Java Developers: Clean Code on Android

Become a professional Kotlin developer and write cleaner code in your Android apps than in Java, avoid boilerplate code

09:14:18 of on-demand video • Updated November 2020

  • Write clean code with Kotlin
  • Avoid ceremony and boilerplate code around Android APIs
  • Use functional programming to write concise, expressive code
  • Create Android apps with Kotlin
  • Write readable SQLite transactions using extension functions in Kotlin
  • Use the Kotlin Android Extensions to avoid findViewById()
  • Create multiple activities, layouts and menus
English Narrator: Alright, now in this lecture we're gonna take a look at one of the major differences in Kotlin when compared to Java. Now more specifically we're gonna talk about nullable types and explicit nullable types. So in Kotlin by default, every type is not nullable which means you can not assign null to it. So let's say we want to create a variable, or let's say a value string and we want this of type String, that in Java you could just assign null to it, which would be fine and would actually be valid for the type String. But you can already see here that we have a red mark, and if I try to run this line, so it's gonna have these squiggly, red lines here, and if I hover over the mark here, over the red mark, it says that null can not be a value of a non-null type String. So this means whenever you have a variable of type String, you can be sure that you never have a null in there. So as long as you're working with normal data types like this, you also can never have a null pointer exception, unless you're interfacing with Java code, which can of course throw null pointer exceptions. So now of course the question is what if you do wanna use null in your code because, well let's say, for some reason you can't avoid it. Well what you can do then is you can say val string, and this should be of type String, but this time nullable and to do this, you put a question mark behind the data type that you wanna use, and then you can also assign null to it. So String question mark is basically the data type, the nullable String data type, which can be any String or null. Now, notice that this holds for every data type in Kotlin. So remember that even integers and doubles are also objects in Kotlin. So you can't assign null to this one, but if you do put a question mark behind the int data type, you can assign null to it. Now, of course the problem with having nulls in your code is that maybe at some point in your code where you're not even sure anymore that an object is null, you try to access a property or a method on that object. So let's say you want to have the length of the string, but that's not gonna work because there's actually no string stored in that object. So you can not call, or you can not get the length of the string. So here in this case, Kotlin is not actually gonna give you a null pointer exception. But what it's gonna do is the compiler's already gonna see that this is invalid. So already at compile-time, which is very important, Kotlin is gonna tell you that this is not valid because you have a nullable type here. So it's unsafe to call any method or property on this object. Now there are two things you can do. So to do it the Java way, which is the better way in this case, is to put two exclamation marks here, and then just call length, or whatever else you wanna have, and that's gonna give it a Kotlin null pointer exception. Now, what string exclamation mark exclamation mark does is it tells the compiler that you're sure that the string object is not gonna be null, and it's your fault if it is indeed null, and you are just wrong at this point. And notice that the double exclamation mark here basically looks like you're screaming at the compiler and this intentional because you shouldn't use this unless you're really sure about this or you it's really necessary, but it's normally not. So let's look at the better way to do this which is the so-called safe call operator. And this is, by the way, the unsafe call operator. So to safely call any method or property on this object here what we're gonna do is we're gonna put a question mark here and then access, well for example, the length. Now in this case, when the object here is null, this is just gonna return null. But in the other case, where let's say string is of type String nullable, but it is indeed not null, but contains some kind of String, so let's say Peter. Then when you call safely the length here, using the question mark, then it's just gonna return the length of the string. So basically this is like an if-then-else. So if the object here is null, then any call you do here is just gonna return null. But if the object is actually not null and has a valid value, then it's just gonna execute the method or get the value of the property that you specify. Now I think this is a great feature in Kotlin because you have null safety at compile time already, which is very different from having the optional or something like that in Java, where you can still at run-time run into the problem of not having an object there. But here as you saw before, if you have nullable type and you try to just call a method on it, it's already not gonna compile, so we have to gonna think about whether you wanna use a safe call or maybe even unsafe call. And there are many other things in which, or many other ways in which, Kotlin makes it much easier to work with such nullable types. One of which I'm gonna show you right now. And others of which we're gonna see later on. So in Kotlin, there's the so-called Elvis operator. And this actually looks like this which is why it's called Elvis operator because if you well, tilt your head to the left, it looks a bit like an Elvis with the special haircut. And the way you're gonna use this is you're gonna say for example, val string length equals, and then you wanna have the length of the string. So string dot length using the safe call operator. And if this is null, you can also easily define now a default value. In this case, let's say if the string is null, we wanna store zero as the length of the string, or you could also store minus one, in order to say that this string was actually not even an empty string, and just to differentiate this and well, using the Elvis operator here is basically a shortcut for checking whether the argument here at the beginning is null and if it is null, assigning the value at the back here and just having this conditional code. So it's a very concise way to do this. So whenever you have a null here, then using the Elvis operator, you can define a default value you wanna use in case you have null in the front. So in this case, we have by now actually defined string. So string length is now gonna be five. But if I go back to assigning the string here like at the top so it's null, and then do this again, so I'm gonna set string length again to this Elvis expression. Then in this case, string length is then just gonna be minus one, which is the default value we wanted to have if the string is null. So this way also, we accomplish that even though string can be null here, string length is always an integer, and not a nullable integer. So we're gonna get rid of null at this point in our code which is of course always a good thing to have. So all in all, in theory, you could use Kotlin without any nulls at all. Without any null pointer exceptions at all as well, but of course in many cases, you're gonna be interoperating with Java code, and in those cases you always have to specify at which points you want to assume a nullable value and at which points you don't want to assume a nullable value. So for example when you call a method that's defined in Java, you can define whether the return value should be nullable or not. And if you're wrong, you're gonna have trouble of course if you say it's not nullable, but then a null is returned. So this is one of the things you have to be aware of when interoperating with Java and we're gonna talk about that later in this course as well. But for now the main takeaways are that every type in Kotlin is not nullable by default. You can add a question mark after the type to specify that it should be nullable. And if you have a nullable type, you should the safe call operator using the question mark, and you should avoid the unsafe call operator using the two exclamation marks. And you can use the Elvis operator to work with nullable values more effectively and to specify default values, for example. Alright so that was one of the first really different aspects when looking at Kotlin when compared to Java. And I hope you found this helpful. If you have any questions about this, of course, let me know in the Q&A, and otherwise I'm gonna see you again in the next lecture.