I have some code where I'm collecting a value from a flow and want to use it to initialize a lateinit variable. I prefer this approach to using a nullable for this case. But although I'm following the instructions here, I am getting an unresolved reference error. Here's some sample code, where the error is on this::arriving
in the conditional test. I suspect the issue is that arriving
is a local variable rather than a class property, but isn't this is supposed to work for local variables as well? What's the right way to reference it?
fun getFavoriteDetail(favorite: Favorite): FavoriteDetails {
lateinit var arriving: Airport
viewModelScope.launch {
flightSearchRepository.getAirportByIata(favorite.destinationCode).collect { airport ->
arriving = airport[0] // Should be only one
}
}
if (this::arriving.isInitialized) {
// Do something useful
}
For now, I can just use a nullable, but I'd appreciate any insight into how to make this work with lateinit isInitialized.
From the documentation here,
To check whether a
lateinit var
has already been initialized, use.isInitialized
on the reference to that property [...]This check is only available for properties that are lexically accessible when declared in the same type, in one of the outer types, or at top level in the same file.
This means that this is not supported for local properties declared in a function. isInitialized
is only available for properties that are declared in a type or at the top level.