I'm wondering if someone can show me the Kotlin-id...
# announcements
j
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:
Copy code
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
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
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
Copy code
repo.getThings()
    .mapNotNull { thing ->
        thing.nullableField?.let {
            SomeOtherThing(
                id = thing.id,
                name = thing.name,
                requiredField = it
            )
        }
    }
j
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
oh i see 👍
j
anyone have any other ways of achieving it?
m
I think
filter
is the best option