简体   繁体   English

Kotlin中的Java接口对象

[英]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: 现在我的MainActivity中有一个方法:

fun onRequestHappen(listener: JSONObjectRequestListener)

If this were java, I would have passed this object as: 如果这是java,我将通过以下对象传递该对象:

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? 如何在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: 并将其传递给您的func,如下所示:

onRequestHappen(listener)

To do this inside the func call you can use the following code snippet: 要在func调用中执行此操作,可以使用以下代码段:

onRequestHappen(object : JSONObjectRequestListener {

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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