How to map() on a function that can return null


#1

I have a function :

foo(a: Integer): Bar?
{
  if( a > 5)
   return Bar()
  return null
}

I want to do something like this:

val list = listOf(1,8)
val barList = list.map {foo(it)}

Of course, I need map() to ignore all null return values. But how do i do that?
Currently the above code wont compile since map() wants a function that returns a non-null value.


#2

It the moment it doesn’t compile for several reasons:

  • fun keyword is omitted and more importantly,
  • Integer is a java type, you should use Int.

Ergo, the following works as expected:

fun main(args: Array<String>) {
    val ints = listOf(1,8)
    val strings = ints.map (::foo)
    
    strings.forEach { println(it) }  
}

fun foo(a: Int): String? = if( a > 5) a.toString() else null

#3

filterNotNull could be useful:

val l = listOf(1, 2, null, 4)
val result = l.filterNotNull()
println(result) // 1, 2, 4

#4

mapNotNull function does exactly what you want https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-not-null.html