且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android Studio将Java转换为Kotlin错误无法推断此参数的类型.请明确指定

更新时间:2023-09-16 08:17:40

到目前为止,您不能使用

As of now, you can't use SAM conversion for interfaces defined in Kotlin. There are a couple things you can do to solve your problem though.

  1. 如果您使用Java定义接口,则SAM转换将开始工作,并且您的当前代码将无需任何其他更改即可工作.

  1. If you define your interface in Java, SAM conversion will start working, and your current code will work without any other changes.

如果要使用接口作为fetch_data方法的参数,并且希望使用Kotlin编写该接口,则必须传入实现该接口的object有点冗长,类似于Java的解决方案:

If you want to use an interface as the parameter of the fetch_data method, and you want it to be written in Kotlin, you'll have to pass in an object that implements it, which is a slightly verbose, Java-like solution:

jmManager.fetch_data(object: OnTaskCompleted {
    override fun onTaskCompleted(theJsonArray: JSONArray) {
        // ...
    }
})

  • 如果您想要一个不错的纯Kotlin解决方案,只需除去接口,并让fetch_data函数将函数作为参数而不是接口作为参数(同样,DataDisplayPage中的当前代码将与此一起工作):

  • If you want a nice pure Kotlin solution, just get rid of the interface, and have the fetch_data function take a function as its parameter instead of the interface (again, your current code in DataDisplayPage will work with this):

    fun fetch_data(callback: (JSONArray) -> Unit) { 
        // ...
        listener?.onTaskCompleted(response)
        callback(response)
        // ...
    }