

The reason is that Java does not support null safety, and non-nullable types do not exist.

In Java, this would not lead to any error, except for a NullPointerException at runtime when trying to call a method or accessing a field on fooString. In Kotlin, this leads to a compilation error because the fooString variable was declared with a non-nullable type. The real difference between Java and Kotlin when dealing with null values becomes clear when trying to give fooString a null value, as follows: fooString = null Let’s see what this means: // fooString is a non-nullable reference This is because Kotlin imposes strict null-safety by default. While initializing a variable in Kotlin as you would in Java, you are using non-nullable types.

On the other hand, the second ones are called nullable references and must be of a nullable type. The first ones are called non-nullable references, and their type must be of a non-nullable type. nullable typesĪs opposed to what happens in Java, Kotlin distinguishes between references that cannot hold null and those that can. So, let’s dive into null safety in Kotlin and learn everything you should know. This is why it is so important to know how to properly use it. This characteristic undoubtedly represents one of the coolest, most beautiful, and innovative features coming with the Kotlin programming language. Kotlin supports this possibility since its first release, and it is called null safety. This way, you can avoid the danger of null references, and you do not have to wait for exceptions or errors to be thrown at runtime. Consequently, any variable cannot contain the null value unless you explicitly say it can. This is why a few programming languages introduced the possibility to indicate that a variable is nullable, or in other words, that it can accept the null value. This leads to several issues that may be difficult to address while programming. One of the most common problems coming with programming languages is that accessing a variable with a null value causes a null reference exception at runtime. A complete guide to null safety in Kotlin Spreading knowledge through writing is my mission. Antonello Zanini Follow I'm a software engineer, but I prefer to call myself a technology bishop.
