Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding multiple interface methods in Kotlin lambda expressions

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.

like image 540
sophia Avatar asked Mar 07 '23 22:03

sophia


1 Answers

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? }
    })
like image 177
Mark Avatar answered Apr 25 '23 13:04

Mark