I have an issue with kotlin on an Android applicat...
# android
p
I have an issue with kotlin on an Android application, I think this is the best channel to ask it:
Copy code
if (parameters[i] != null) {
    if (parameters[i].isNotEmpty()) {
Why this gives error on .isNotEmpty()? I mean... it's supposed that the != null should about this problem:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
m
I don't know what type
parameters
is, but I will assume that the compiler cannot assume that
parameters[i]
returns the same value every time you call it, so smart cast is not happening.
p
is a String?
m
paramaters
is a
String
or
parameters[i]
is a
String
? But still the
[]
operator is a function call and there's no guarantee that it returns the same object every time. Now Kotlin could hard take advantage that
String
is immutable, but
String.get
cannot return
null
so there's no need, so I"m sure
parameters
is not a
String
. It is probably either a
List
or an
Array
both of which are not immutable.
p
parameters[i] contains String?
is an array of String?
m
So since arrays are not immutable, the compiler cannot smart cast the returned string.
l
It's possible that another thread has access to 'parameters' and can set it to null between the check and usage. It's safer to create a local variable, which the compiler can guarantee won't be modified concurrently, and will smart cast for you.
c
Capture the value from the array in a variable then the compiler can assess it as you're expecting:
Copy code
val myValue = parameters[i]
if (myValue != null) {
    if (myValue.isNotEmpty()) {
        // .....
    }
}
Or alternatively:
Copy code
val myValue = parameters[i]
if (myValue.isNullOrEmpty()) {
    // ....
}
h
Or use let parameters[i]?.let { nonNullValue -> }
c
.let
is a functional mapper. If you are not interested in the return value, then that's not its best use case. It should not be a default replacement for a standard null check
1