https://kotlinlang.org logo
Title
j

james

11/14/2019, 11:45 PM
I'm wondering if someone can show me the Kotlin-idiomatic way to solve the following. I have a list of objects which gets returned from a repo and I'd like to transform them into another object, while throwing away objects that are deemed "invalid".. where invalid in this example is if
it.nullableField
is null. I've tried the following, but it doesn't work as expected because the smart cast fails, as seen in comment:
repo.getThings()
    .mapNotNull {
        if (it.nullableField != null) {
            SomeOtherThing(
                id = it.id,
                name = it.name,
                requiredField = it.nullableField // compiler error: Smart cast to String is impossible because it.nullableField is a public API property declared in a different module
            )
        } else null
    }
s

streetsofboston

11/14/2019, 11:48 PM
Insert a
.filter { it.nullableField != null }
into the chain. Then just do
.map { SomeOtherThing( ..., ..., requiredField = it.nullableField!!) }
You still would need the
!!
check; smart-casting won’t work in this case
j

james

11/14/2019, 11:49 PM
I considered that, and I considered just adding !! to
it.nullableField
where my comment is. both of these seem to work, but I'm wondering what the idiomatic way is?
using
filter
feels more readable at least
b

basher

11/14/2019, 11:51 PM
repo.getThings()
    .mapNotNull { thing ->
        thing.nullableField?.let {
            SomeOtherThing(
                id = thing.id,
                name = thing.name,
                requiredField = it
            )
        }
    }
j

james

11/14/2019, 11:58 PM
I considered that too, Ben, but my main concern there is that it limits me to a single field being checked.
I'm leaning towards using
filter
b

basher

11/14/2019, 11:58 PM
oh i see 👍
j

james

11/14/2019, 11:58 PM
anyone have any other ways of achieving it?
m

Matteo Mirk

11/19/2019, 12:29 PM
I think
filter
is the best option