Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin filterNotNull for object properties

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

like image 809
hughjdavey Avatar asked Oct 16 '22 21:10

hughjdavey


1 Answers

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.)

like image 60
yole Avatar answered Oct 27 '22 10:10

yole