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

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 = {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.

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 = (::foo)
    strings.forEach { println(it) }  

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

filterNotNull could be useful:

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

mapNotNull function does exactly what you want mapNotNull - Kotlin Programming Language