I have the following (simplified) kotlin code:
data class Event(val name: String, val venue: Venue?)
data class Venue(val lat: Double, val lng: Double)
...
return events
.filter { it.venue != null }
.map { doSomething(it.venue.lat, it.venue.lng)
The code doesn't compile with the error Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Venue?
I understand what this means, but I don't understand why the compiler can't figure out that it.venue
cannot be null
in the .map
call.
If the event were nullable, I could write events.filterNotNull().name
or something and the compiler would not complain. Is there any way to do the same for a nullable object property rather than a nullable object?
Thanks for your time
No, this is not possible, either in the current version of Kotlin or with any of the potential enhancements currently being considered. The Kotlin compiler is not smart enough to understand the semantics of the filter
function and to know that the check performed in the lambda passed to that function will affect the possible types in a different lambda.
(There is not even a possibility to express the idea of "a collection of Event where Event.venue is not null" as a Kotlin type, much less to infer that the receiver of map
will have that type.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With