Using the 'mapNotNull' Function for Transforming and Filtering Collections

The 'mapNotNull' function is a powerful tool in Kotlin that allows you to transform a collection while simultaneously filtering out any null values that may result from the transformation process. This is particularly useful when you have a collection of items and you want to apply a transformation that may produce nulls, but you only want to keep the non-null results.

val names = listOf("Alice", "Bob", null, "David", null, "Eva")

// Transforming names to their lengths while filtering out nulls
val nameLengths = names.mapNotNull { it?.length }

println(nameLengths) // Output: [5, 3, 5]