20.2 Nullity and Java libraries
Ok, so the previous explanation works perfectly well with Kotlin code. But what happens with Java
libraries in general, and Android SDK in particular? In Java, every object can be null by definition.
So we would have to deal with a lot potentially null variables which in real life are never null. This
means our code could end up with hundreds of
!!
operators, which is not a good idea at all.
When you are dealing with the Android SDK, you’ll probably see that many parameters are marked
with a single ‘
!
’ when any Java methods are used. For instance, something that gets an
Object
in
Java will be represented as
Any!
in Kotlin. This means that it’s up to the developer to decide whether
that variable should be null or not.
Luckily, latest versions of Android are starting using the
@Nullable
and
@NonNull
annotations to
identify the parameters that can be null or the functions that can return null, and the Kotlin compiler
is able to detect that and choose the appropriate translation into Kotlin language.
Said that, if we are for instance overriding
onCreate
for an
Activity
, we need to mark
savedIn-
stanceState
as nullable:
1
override fun onCreate(savedInstanceState: Bundle?) {
2
}
Otherwise it will show an error. We can’t use this implementation:
20 Null safety in Kotlin
92
1
override fun onCreate(savedInstanceState: Bundle) {
2
}
This is great, because an activity can perfectly receive a null bundle and we get the right
implementation for free. But there are parts of the SDK that are not properly annotated yet. So
when in doubt, you can just use a nullable object and deal with the possible
null
. Remember, if you
use
!!
it’s because you are sure that the object can’t be null, so just declare it as non-nullable.
Do'stlaringiz bilan baham: |