Sparker0i
Sparker0i

Reputation: 1851

Java Interface Objects in Kotlin

Consider I have an interface like the one below:

interface JSONObjectRequestListener {
    fun onSuccess()
    fun onFailure()
}

Now I have a method in my MainActivity:

fun onRequestHappen(listener: JSONObjectRequestListener)

If this were java, I would have passed this object as:

onRequestHappen(new JSONObjectRequestListener() {
    @Override
    public void onResponse() {
        // do anything with response
    }

    @Override
    public void onError() {
        // handle error
    }
});

How do I pass this interface's object in Kotlin?

NB. Please don't mark this as a duplicate of this as what that question requests is completely different from what I want

Upvotes: 0

Views: 119

Answers (1)

savepopulation
savepopulation

Reputation: 11921

You can define your listener like this:

val listener = object : JSONObjectRequestListener {

    override fun onResponse() {
        // do anything with response
    }

    override fun onError() {
        // handle error
    }
}

And pass it to your func like below:

onRequestHappen(listener)

To do this inside the func call you can use the following code snippet:

onRequestHappen(object : JSONObjectRequestListener {

        override fun onResponse() {
            // do anything with response
        }

        override fun onError() {
            // handle error
        }
    })

Upvotes: 3

Related Questions