I'm new to Android development (started 6 months ago) and would like to move from Java to Kotlin. I've converted my project to Kotlin and fixed all issues but one and I can't figure out how to fix it.

I'm attempting to retrieve a JSONArray (as seen in class JsonManager) and use the retrieved data in a second class called DataDisplayPage via a method call.

I am getting the following console errors, which occur at this line of the second class: jManager.fetch_data{ theJsonArray ->.

Cannot infer a type for this parameter. Please specify it explicitly.

Type mismatch: inferred type is (???) -> Unit but OnTaskCompleted was expected

First class JsonManager

interface OnTaskCompleted {
    fun onTaskCompleted(theJsonArray: JSONArray)
}

class JsonManager {
    var listener: OnTaskCompleted? = null

    init {
        Log.d("JsonManager", "Instance created")
    }

    fun fetch_data(callback : OnTaskCompleted) {
        listener = callback
         val url ="https://someURL"

        AndroidNetworking.get(url)
            .build()
            .getAsJSONArray(object : JSONArrayRequestListener {
                override fun onResponse(response: JSONArray) {
                    listener?.onTaskCompleted(response)
                }

                override fun onError(anError: ANError) {
                    Log.d("error", anError.toString())
                }
            })

}

二级数据显示页面

class DataDisplayPage : AppCompatActivity()

    fun onStartUp() {

        val jManager = JsonManager()

        jManager.fetch_data{ theJsonArray  ->
            val newData = DepData()
            newData.setCellData(theJsonArray as JSONArray)
        }
    }
}

推荐答案

到目前为止,在Kotlin中定义的接口不能使用SAM conversion.不过,你可以做一些事情来解决你的问题.

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

  2. 如果您希望使用接口作为fetch_data方法的参数,并且希望它用Kotlin编写,则必须传入实现它的object,这是一个有点冗长的、类似Java的解决方案:

    jmManager.fetch_data(object: OnTaskCompleted {
        override fun onTaskCompleted(theJsonArray: JSONArray) {
            // ...
        }
    })
    
  3. 如果您想要一个很好的纯Kotlin解决方案,只需go 掉接口,让fetch_data函数接受一个函数作为其参数,而不是接口(同样,您在DataDisplayPage中的当前代码也可以使用此接口):

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

Kotlin相关问答推荐

关键字';在When Kotlin When-语句中

如何检测一个值是否是Kotlin中的枚举实例?

哪个更好? Integer.valueOf(readLine()) 或 readLine()!!.toInt()

使函数同时挂起和取消挂起

为何Kotlin标准库中的AND和OR函数不能像&&和||一样进行短路运算?

在协程上下文中重新抛出异常

如何在 Android Jetpack Compose 中的画布上绘制一侧加厚的描边?

如何在 Kotlin 中不受约束?

如何在 Kotlin 中实现 Composition UML 关系?

Kotlin 静态函数:伴生对象,@JvmStatic @JvmField

在 Spring Framework 5.1 中注册具有相同名称的测试 bean

retrofit 响应代码 405 并带有消息method not allowed here

无法创建类 ViewModel kotlin 的实例

取消信号上的kotlin流量采集

Kotlin协程处理错误和实现

Android EditText 协程go 抖操作符,如 RxJava

如何序列化/反序列化Kotlin密封类?

Dagger +Kotlin 不注入

查找是否在列表中找到具有特定属性值的元素

在多平台子元素中使用kapt