-
Book Overview & Buying
-
Table Of Contents
Android Programming for Beginners - Fourth Edition
By :
There is nothing wrong with a null value, but null values, as I just said, cause crashes when we accidentally try to access them, and therefore, we should only use null when unavoidable, and when we do, we should use it carefully. Kotlin, as we will see, has a whole system for handling null values.
Let's explore the Java problem a bit first, and then we can better understand the Kotlin solution later. Look at the following example of some simple Java code. A brief explanation is required before looking at the Java code. The Integer type in Java is a class that wraps the basic primitive type int. We haven't seen this in Kotlin because all types in Kotlin are classes that wrap a basic primitive type. The int keyword is a simple primitive type that can hold only integer values and cannot be null.
Integer someInt = null;
int anotherInt = someInt; // Throws NullPointerException
On the first line of the preceding code, we declare the Java equivalent of a Kotlin...