0

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

1 Answer 1

3

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
        }
    })
Sign up to request clarification or add additional context in comments.

1 Comment

Is there no way to do it inside the function call?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.