I have `val articles: List<ArticlesItem?>? =...
# getting-started
s
I have
val articles: List<ArticlesItem?>? = null
as part of my JSON response. I am trying to pull data off this list using
articles[position]
but Android Studio complains that
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type List<ArticlesItem?>?
. Why can I do
newsDataSet!![position]
but not
newsDataSet?[position]
?
val articlesItem: ArticlesItem? = newsDataSet[position]
full code https://github.com/sudhirkhanger/Samachar/blob/911f934252409e9a726e30a4865518e738042c93/app/src/main/java/com/sudhirkhanger/newsapp/ui/list/NewsListAdapter.kt#L45
s
I think it was just a weird part of the grammar that probably wasn’t trivial to address. you do have the option to use
newsDataSet?.get(position)
though
s
Thanks. That did work. Another question that I have is If I am in a situation where I am unsure of what I might end up with like in the case of
val articles
at the top do I have to just safe calls everywhere possible to avoid NPE.
p
Instead of safe call you can also write:
Copy code
if (articles != null) {
    articles[position]
}
or
Copy code
articles ?: return
articles[position]
or
Copy code
articles?.let {
    it[position]
}
You can check that
articles
is not null in any way you want 🙂
👆 1