List containing nullable values to a nullable List in Kotlin
<p>I have a <code>List&lt;T?&gt;</code> 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 <code>sequence</code>). The following pseudocode demonstrates what I want to do:</p>

<pre><code>fun &lt;T&gt; sequence(a : List&lt;T?&gt;) : List&lt;T&gt;? {
    return 
        a.fold(
            listOf(),
            { 
                prevArray, element -&gt; 
                    if(element == null) null else prevArray + element 
            })
}
</code></pre>

<p>This is pseudocode because the compiler complains that <code>Null can not be a value of a non-null type kotlin.collections.List&lt;T&gt;</code>.</p>

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

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

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