Search code examples
androidnullkotlinnon-nullable

why android studio required to Add non null Asserted(!!) call even after safety is added in Kotlin


enter image description here

it denote List of Object in the Image. here checking list is not empty. but showing an error to add (?) safety . but again show an error to add non null Asserted(!!) even add safety.
error can fix only after add this.

 if (it?.isNotEmpty()!!) {
    //do your work here
 }

why android studio required to Add non null Asserted (!!) call .


Solution

  • Your it is nullable (hence the ? after it). So the statement becomes, in plain English, "if it is not null, is it not empty?", which is a Boolean. However, what if it is null?

    Your evaluation of it?.isNotEmpty() produces a Boolean?, which is not accepted in an if.

    So one possible solution is to say "I know it won't be null at that time" and so replace with it!!.isNotEmpty().

    Another option is to break down your if statement furthermore, like such :

    if (it != null && it.isNotEmpty())