Kotlin is there a map function for nullable values

49 views Asked by At

I want to map a nullable value, apply a function inside the value if exists, if not return null.

1

There are 1 answers

1
developer_hatch On

I end up creating an extension function:

fun <A, B> A?.mapNullable(f: (A) -> B): B? = if (this == null) null else f(this)

and you can use it like

nullValue.mapNullable { it.something }

Finally this is exactly the same to do nullValue?.let {...}