Say I have a Callbacks
interface with two methods onCurrentLocation
and onError
:
public interface Callbacks {
void onCurrentLocation(ClientLocation location);
void onError();
}
and a class that takes this interface in its constructor, say:
public MyLocationClient(Callbacks callbacks) {...}
Now, in Kotlin, should I be able to instantiate MyLocationClient this way:
val myLocationClient = MyLocationClient(
{ location: ClientLocation ->
updateClientLocation(location)
},
{})
and if not, why not?
The behavior I'm seeing is: When the interface only has one method, the construction of this object compiles fine. But, as soon as I add more methods to Callbacks
, the compiler complains
"Type mismatch. Required: Callbacks! Found: (ClientLocation) -> Unit"
Edit: removed the null check for location
since it was irrelevant to the question.
So you're creating an instance on an anonymous class that is not a functional interface (they only have one method) so it would be something like :
val myLocationClient = MyLocationClient(object : Callbacks {
override fun onCurrentLocation(location : ClientLocation?){
location?.run{ updateLocation(this) }
}
override fun onError(){ // should you not handle errors? }
})
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