Next up, let's see how we can map one value to another value. Let's map our string, "Kotlin", to a corresponding data type.
First, we'll create a sealed class to represent our programming languages:
sealed class ProgrammingLanguage(protected val name: String) {
object Kotlin : ProgrammingLanguage("Kotlin")
object Java : ProgrammingLanguage("Java")
object Swift : ProgrammingLanguage("Swift")
override fun toString(): String {
return "$name Programming Language"
}
}
Next, we can add a call to the map() function to map our String items to a corresponding language. The map operator allows us to change our result type from the incoming data type to any outgoing data type we wish. In this case, we are mapping from String to ProgrammingLanguage:
val list = listOf("Kotlin", "Java", "Swift", "K")
list.filter { it.startsWith("K") }
.map {
when (it) {
"Kotlin" -> ProgrammingLanguage.Kotlin
else -> null
}
}
.forEach { println(it) }
If we run this, we'll get the following output:
Kotlin Programming Language
null
Notice that we are seeing null printed to the console since we are unable to map the string "K" to ProgrammingLanguage and thus return null.
To address this, we can make use of another function, filterNotNull(), to filter out any values that are null:
val list = listOf("Kotlin", "Java", "Swift", "K")
list.filter { it.startsWith("K") }
.map {
when (it) {
"Kotlin" -> ProgrammingLanguage.Kotlin
else -> null
}
}
.filterNotNull()
.forEach { println(it) }
If we now run this code, we'll see only the non-null values:
Kotlin Programming Language
The map() function is quite powerful as it lets us change the nature of a data flow or map multiple values to a known set of values or types.