Home > Back-end >  Valid to add null to listOfNotNull()?
Valid to add null to listOfNotNull()?

Time:03-31

I've read following:

listOfNotNull(
    if (isSomeCondition) {
        ListSomeItem(123)
    } else null
)

Creating listOfNotNull() with a null in it? Is this valid?

CodePudding user response:

If your condition isSomeCondition is false the list will not insert the null value and it will be empty

Check this example

val list = listOfNotNull(null)
print(list.size)

The output will be zero

And in this example

val list = listOfNotNull(null, null, 1, null)
print(list.size)

Only 1 will be inserted and the size will be 1

Basically, listOfNotNull will filter the values and create a list from the non nulls values

The source code of listOfNotNull

public fun <T : Any> listOfNotNull(vararg elements: T?): List<T> = elements.filterNotNull()

So your code will be like insert or be empty

  • Related