0

I have a piece of code that parses and arbitrary document.

if (page.title != null && page.text != null && page.timestamp != null && size != null) {
    parseTitle(page.title)
    parseText(page.text)
}

Despite the implicit null checks, compiler still says that page.title and page.text are both nullable.

Can someone explain why that happens?

  • Are any of these `var`? – Michael Jan 12 '22 at 13:59
  • they are all var's, yeah – Artem Shashulovskiy Jan 12 '22 at 13:59
  • See the last paragraph in this section: https://kotlinlang.org/docs/null-safety.html#checking-for-null-in-conditions – Michael Jan 12 '22 at 14:03
  • 2
    I’ll just comment since I know this question is a duplicate but I’m on mobile so it’s hard to search quickly. If `page` is a property rather than local variable or if `title` and `text` are mutable properties (`var`), then it’s possible for their values to have changed in between the null check and the next time you access them, so the compiler cannot assume they are non-null. Copy their values to local variables first and then null-check and use those local variables. – Tenfour04 Jan 12 '22 at 14:30
  • Also, those null checks are explicit, the opposite of implicit :) – Joffrey Jan 12 '22 at 15:10

0 Answers0