Is there a way to convey the fact that while incom...
# codereview
a
Is there a way to convey the fact that while incoming T is nullable, it is not nullable in the outcome of the following:
Copy code
fun<T> List<T>.indexedNotNull(): List<Pair<Int, T>> = this.mapIndexedNotNull { index, t -> 
    t?.let{ index to t }
}
j
You can use the notation
T & Any
, it's the only denotable intersection type for now, but that's the one you need so you're lucky :)
e
you could do that, but
Copy code
fun <T: Any> List<T?>.indexedNotNull(): List<Pair<Int, T>>
represents that fine (in the same way that
.filterNotNull()
does)
gratitude thank you 1
👍 2
come to think of it, the built-in
.withIndex()
is lazy, which you could also replicate pretty easily
Copy code
fun <T: Any> Iterable<T?>.indexedNotNull(): Iterable<IndexedValue<T>> = Iterable {
    iterator {
        forEachIndexed { index, value ->
            if (value != null) yield(IndexedValue(index, value))
        }
    }
}
gratitude thank you 1
a
TIL about
forEachIndexed