Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Valid to add null to listOfNotNull()?

I’ve read following:

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading