Search code examples
kotlinoption-typearrow-kt

Map list of Options to list of Strings


I've been using Arrow Kotlin quite a lot recently but I'm still confused on how to map a list of options to their values. For example:

val listOfStrings: List<String> = listOf<Option<String>>().map { /* ? */ }

Currently I'm doing it like this:

val listOfStrings: List<String> = listOf<Option<String>>().filter { it.isDefined() }.map { it.getOrElse { "" } }

But it feels clunky and I'm surely missing something.


Solution

  • You want Haskell's catMaybes. :D
    I don't know if there's something similar in Arrow, but you could use filterMap from arrow.core.extensions.list.monadFilter.filterMap:

    fun main() {
        val list = listOf(Some(1), None)
    
        println(list.filterMap(::identity))
    }
    // prints: ListK(list=[1])