简体   繁体   中英

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

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
        }
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM