List containing nullable values to a nullable List in Kotlin

Viewed 6220

I have a List<T?> containing null values (which, I suppose, is not forbidden). If one element of this list is null, I want the entire list to be null (what Haskell people call sequence). The following pseudocode demonstrates what I want to do:

fun <T> sequence(a : List<T?>) : List<T>? {
    return 
        a.fold(
            listOf(),
            { 
                prevArray, element -> 
                    if(element == null) null else prevArray + element 
            })
}

This is pseudocode because the compiler complains that Null can not be a value of a non-null type kotlin.collections.List<T>.

What's the idiomatic way to express what I want to in Kotlin? Using Java's Optional type, this is at least compilable:

fun <T> sequence(a : List<T?>) : Optional<List<T>> {
    return 
        a.fold(
            Optional.of(listOf()),
            { 
                prevArray, element -> 
                    if(element == null) Optional.empty<List<T>>() else Optional.of(prevArray + element) 
            })
}

But Kotlin has many operators and functionalities regarding null handling, so I thought using null directly would be more idiomatic.

2 Answers

Using Konad library you can now do the following:

fun <T> sequence(a : List<T?>) : List<T>? = a.flatten()?.toList()
Related