Null safety

Nullability is one of the reasons that most applications crash. Kotlin is very strict when it comes to safety. Every application user (especially mobile users) want a nice, simple, and smooth user experience. An application that crashes makes more than 90% of users frustrated, causing them to instantly uninstall the application.

See the following example of Java. Here, the variable name is assigned a null value, which is the correct syntax in Java:

String name = null; // OK in java
int length = name.length(); // application crashed

But when name.length will be executed, Java will throw NullPointerException. In Kotlin, it is very important to note that variables are non-nullable by default and we cannot assign null values to them. Let's take a look at an example and assign a null value to a variable as follows:

var notNull : String = null

If we try to assign a null value to a variable, the compiler will immediately throw an error:

Error: "Null cannot be a value of a non-null type String".

At the time of declaration, a value must be assigned to the variable as follows:

var notNull : String = "Hello"

It is now safe to use the length function. The length is a function provided by Kotlin that returns the length of a string:

var length = notNull.length

Kotlin is compatible with Java, and we can write both Kotlin and Java code in one application (see Chapter 8, Interoperability). Java is not a null-safe language, and because of this, Kotlin designers enable programmers to assign null values by defining a nullable variable:

var mayBeNull : String? = null

Adding a question mark to a command indicates to the compiler that a null value can be assigned to the variable:

fun main(args: Array<String>) {
var notNull : String = "Hello"
notNull = null // not allowed

var len = notNull.length
println("Value is $notNull and length is ${notNull.length} ")

var mayBeNull : String?
mayBeNull = null // allowed
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.12.34