Hi, I have a silly question. Can a list of non-nul...
# announcements
w
Hi, I have a silly question. Can a list of non-null type ever be possible to contain null value somehow?
d
In a Java environment, certainly.
You will get a descriptive exception thrown when accessing the list from Kotlin though
w
can you please give an example? thanks
d
Java code:
Copy code
class Evil {
  public static void beEvil(List<String> list) {
    list.add(null);
  }
}
In Kotlin:
Copy code
fun main() {
    val list = mutableListOf<String>()
    Evil.beEvil(list)
    println(list[0]) // throws an exception
}
w
yeah, I’m indeed using Kotlin + Java. The example definitely make senes but the NPE from a non-null type list is certainly from Kotlin code only.
Thus I’m super confused…
d
Yes, Java has no non-null types, hence there is no way for Java code to throw
w
I think my question should be . In Kotlin environment, I’m seeing NPE from iterating non-null list.
d
Then some Java code put null into the list.
From the Kotlin side you must ensure that you don't pass a non-null list where Java might add a null.
w
umm…it’s unlikely Java code. Could it ever be Kotlin?
I checked, no Java code is modifying that list, very weird
b
do you use the JVM stdlib?
w
it’s on Android, so I guess yes?
b
my guess is that the NPE is thrown from Java code that is probably related to the implementation that you use
next guess would be concurrency
race condition
w
NPE is actually from Kotlin code. And how can concurrency inject null value into non-null list?
b
it depends on how well the abstraction holds
and if things are atomic
do you have a stack strace btw?
w
my issue is almost same as this one
b
that uses an ArrayList which is jvm
afaik
ok, could be both
@SinceKotlin("1.1") public actual typealias ArrayList<E> = java.util.ArrayList<E>
ok, so the built in ArrayList is just an alias for the jvm one
can you try to use a thread safe array list
check if that fixes it. if it does it's a concurrency issue
w
yeah, guess this is the only thing I can do
b
my guess is some jvm code is modifying your list in whatever way
or it's really an android/jvm bug which I doubt
w
yeah, I’m more leaning towards concurrency issue too. Very hard to reproduce it.
g
One more dirty workaround consider list values as nullable if this possible for your code, but it may hide real bug in some cases