-
Book Overview & Buying
-
Table Of Contents
Android Programming for Beginners - Fourth Edition
By :
We have established that null values are potentially hazardous, but we also know we will regularly require them. What we need to do, then, is explore how to work safely with them. First, consider this code:
val i1 : Int = 2
val i2 : Int = 2
val answer = i1 + i2
Log.d("Nullability", "The answer is $answer")
You are probably aware that the code above creates two integer values, adds them, and outputs The answer is 4 to the logcat. But let's change it a bit. Consider this code:
val i1 : Int = 2
val i2 : Int? = null
val answer = i1 + i2
Log.d("Nullability", "The answer is $answer")
In the preceding code, there will be an error in Android Studio. We have a type-mismatch error, reported by Android Studio: Required Int found Int?. The error is on the i2 of this line of code.
val answer = i1 + i2
The error occurs because we are using a nullable value, and we must handle the possible (in this case, the actual) null case explicitly...