Issue
In Android, there is a android.location.LocationListener
class, and the Android Operating System updates locations using the class as below:
It says that Location is @NonNull, but in reality the OS does return null sometimes, which crashes the app.
object : LocationListener {
override fun onLocationChanged(location: Location) {
doSomethingWithLocation(location) // App crashes here, because location is null
}
}
Is there some way to tell the compiler that Location
is actually Location?
?
Solution
I found two workarounds for this.
First, if the interface contains only a single abstract method, we can use SAM conversion and override the type of the parameter to Location?
like this:
val listener = LocationListener { location: Location? ->
doSomethingWithLocation(location)
}
What is interesting, we can override the parameter if using SAM conversion, but we can't if using full syntax of subtyping. It seems LocationListener
is SAM, so this solution could work in your case.
If the first solution is not possible, we can override the interface in Java:
public interface MyLocationListener extends LocationListener {
@Override
void onLocationChanged(@Nullable Location location);
}
val listener = object : MyLocationListener {
override fun onLocationChanged(location: Location?) {
doSomethingWithLocation(location)
}
}
Answered By - broot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.