Android Studio converts Java to Kotlin error The type cannot be inferred for this parameter. Please state this explicitly
I'm new to Android development (started 6 months ago) and would like to migrate from Java to Kotlin. I converted my project to Kotlin and fixed all problems but one and I can't figure out how to fix it.
I am trying to get a JSONArray (as seen from the JsonManager class) and use the received data in a second DataDisplayPage class via a method call.
I get the following error console, which are found in this line of the second class: jManager.fetch_data{ theJsonArray ->
.
The type cannot be inferred for this parameter. Please state this explicitly.
Type mismatch: inferred type is (???) -> Expected but Expected OnTaskCompleted
First JsonManager class
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())
}
})
}
Second DataDisplayPage class
class DataDisplayPage : AppCompatActivity()
fun onStartUp() {
val jManager = JsonManager()
jManager.fetch_data{ theJsonArray ->
val newData = DepData()
newData.setCellData(theJsonArray as JSONArray)
}
}
}
source to share
At the moment, you cannot use SAM conversion for interfaces defined in Kotlin. There are several things you can do to fix your problem.
-
If you define your interface in Java, the SAM transformation will start and your current code will work without any changes.
-
If you want to use an interface as a method parameter
fetch_data
, and you want it to be written in Kotlin, you will need to passobject
in that implements it, which is a slightly verbose, Java-like solution:jmManager.fetch_data(object: OnTaskCompleted { override fun onTaskCompleted(theJsonArray: JSONArray) { // ... } })
-
If you want a good clean Kotlin solution, just get rid of the interface and the function
fetch_data
will take the function as its parameter instead of the interface (again, your current code inDataDisplayPage
will work with this):fun fetch_data(callback: (JSONArray) -> Unit) { // ...
listener?.onTaskCompleted(response)callback(response) // ... }
source to share