What would be an idiomatic way of only adding an item to a map if it's not null?
Copy code
val item1: String = ""
val item2: String? = getItem2()
val map = mapOf(1 to item1, 2 to item2) //only if item2 is not null
d
Dominaezzz
01/08/2019, 3:19 PM
For that exact use case.
val map = if (item2 != null) mapOf(1 to item1, 2 to item2) else mapOf(1 to item1)
.
Dominaezzz
01/08/2019, 3:22 PM
For anything more complex, I'd use mapOf then filter the nulls out. If there are possible key conflicts, then a MutableMap instead.
m
Matheus
01/08/2019, 3:27 PM
something like this?
Copy code
mapOf(1 to item1, 2 to item2)
.filter {it.value != null}
.map{ Pair(it.key, it.value!!)}
d
Dominaezzz
01/08/2019, 3:31 PM
Yeah or
Copy code
map.filterValues { it != null }
.mapValues { it.value!! }
.
a
Artem Golovko
01/08/2019, 3:31 PM
You can use like this
Copy code
fun main() {
val allItems = listOf(
"",
getItem2()
)
val map = allItems.filterNotNull().mapIndexed { index, el -> index to el }
}
fun getItem2(): String? {
val rnd = Random.nextInt()
if (rnd % 2 == 0) {
return "Not null string"
}
return null
}