as in: ``` listOfObjects .filter { it.field !=...
# announcements
b
as in:
Copy code
listOfObjects
    .filter { it.field != null }
    .map { it.field.method() }
t
Isn't using !! in this case null-safe technically?
b
yes
.map { it.field!!.method() }
filterNonNull only works if you keep the filtered value
an other example would be
Copy code
listOfObjects
    .filter { it.field != null }
    .map { if (it.field.method()) it.nonNullField else it.otherNonNullField }
t
Maybe you could implement a wrapper of .filter() with a contract implying that returned values aren't null
don't know how that'd happen though, never used contracts
b
afaik you cant nest contracts
as in: you can create a contract based on an object
e.g. if returns true then input object was not null
but I don't think you can imply that a field on the input object is not null if the method returns true
h
There isn't a way to do this AFAIK
b
the only way that I found to circumvent this stuff is to pull all the needed values out into tuples
p
Maybe this?
Copy code
listOfObjects
    .mapNotNull { it.field }
    .map { it.method() }
h
Doesnt solve his second example though
I try not to use
!!
, but this seems like a legit use of it
b
it's pretty much the only issue that I've encountered where I needed !!
h
My next suggestion was going to be
Pair
but sounds like youve done that. I prefer !! tbh
b
right, wrapping and unwrapping it is a bit less readable imho
h
Yeah
Definitely harder to reason about what the code is doing when its wrapping and unwrapping tuples to get at the data.
b
interesting thing is that this already works for simple logic:
Copy code
data class Struct(val value: String?)

fun main(args: Array<String>) {
    val s = Struct("hi")
    if (s.value != null) 
        println(s.value.length)
}
I'll open a ticket
o
May be like this
listOfObjects.mapNotNull { it.field?.let { field -> if (field.method()) it.nonNullField else it.otherNonNullField } }
b
right, but that approach leads to code where you can't really make use of map and filter anymore
you can ofc also solve this issue by not using map/filter at all and go for a forloop and if
p
I think
filterNotNull
does not need a contract as it returns not nullable collection.
☝️ 2
b
yes, as an unchecked cast
g
This is more efficient and shorter
Copy code
.mapNotNull { it.field?.method() }