What would be an idiomatic way of only adding an i...
# getting-started
m
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
For that exact use case.
val map = if (item2 != null) mapOf(1 to item1, 2 to item2) else mapOf(1 to item1)
.
For anything more complex, I'd use mapOf then filter the nulls out. If there are possible key conflicts, then a MutableMap instead.
m
something like this?
Copy code
mapOf(1 to item1, 2 to item2)
   .filter {it.value != null}
   .map{ Pair(it.key, it.value!!)}
d
Yeah or
Copy code
map.filterValues { it != null }
    .mapValues { it.value!! }
.
a
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
}
m
Nice! Thanks, guys! @Artem Golovko @Dominaezzz