Home > Net >  More concise way to return null if list is empty
More concise way to return null if list is empty

Time:10-03

I currently have some Jetpack Compose code similar to this:

val filteredList: List<String> = someList.filter { // some condition }
someState.value = if(filteredList.isNotEmpty()) filteredList else null

I filter a list using some condition, then set some state equal to that filtered list. However, if the filtered list is empty, I want the state to be set to null.

This code works, but I'm wondering if there is a more concise way to do this in Kotlin? I've tried playing around with the scope functions, but I couldn't figure out how to return the null value when the filtered list was empty.

CodePudding user response:

A more concise way would be to use ifEmpty, which returns a default value (in this case you'd want null) if the list is empty or else the list itself;

someState.value = filteredList.ifEmpty { null }

A Kotlin Playground to play with

CodePudding user response:

You can use takeIf() extension:

someList.filter { ... }.takeIf { it.isNotEmpty() }
  • Related