如果列表为空则返回 null 的更简洁方法

ich*_*en2 2 kotlin android-jetpack-compose

我目前有一些与此类似的 Jetpack Compose 代码:

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

我使用某些条件过滤列表,然后将某些状态设置为等于该过滤列表。但是,如果过滤列表为空,我希望将状态设置为空。

这段代码可以工作,但我想知道在 Kotlin 中是否有更简洁的方法来做到这一点?我尝试过使用作用域函数,但我无法弄清楚当过滤列表为空时如何返回空值。

Joa*_*son 8

更简洁的方法是使用ifEmpty,如果列表为空或列表本身,它会返回默认值(在本例中您需要 null);

someState.value = filteredList.ifEmpty { null }
Run Code Online (Sandbox Code Playgroud)

一个可以玩的 Kotlin 游乐场