I am converting an Android app that was originally written in Java to Kotlin. I am struggling to understand the following error message:
Type mismatch. Required: MenuSlidingTabStrip.OnTabSelectedListener? Found: (Nothing, Nothing) → Boolean
Here is the fragment of code where the error is being signalled (and it was working perfectly fine before the conversion):
private var tabs: MenuSlidingTabStrip? = null //The Kotlinized class
tabs!!.setOnTabSelectedListner{ tab, category -> /*Type mismatch...*/
listView!!.post {
...
}
}
The issue arose after converting this Java code (found in MenuSlidingTabStrip) :
public void setOnTabSelectedListner(OnTabSelectedListener listener) {
this.listener = listener;
}
public interface OnTabSelectedListener {
public void OnTabSelected(View tab, MenuCategory category);
}
To Kotlin
fun setOnTabSelectedListner(listener: OnTabSelectedListener?) {
this.listener = listener
}
interface OnTabSelectedListener {
fun onTabSelected(tab: View?, category: MenuCategory?)
}
Can you see the issue? Do you need more code?
I'd suggest you to use the natively supported lambdas as:
// make `this.listener` look like lambda signature as well
fun setOnTabSelectedListner(listener: (tab: View?, category: MenuCategory?) -> Unit) {
this.listener = listener
}
tabs!!.setOnTabSelectedListner { tab, category ->
// ...
}
If you still wanna use the SAM conversion with the manually defined interface, then mark the interface with the fun
keyword as described in Kotlin 1.4-M1 Release changelog (will only work with Kotlin 1.4):
fun interface OnTabSelectedListener {
fun onTabSelected(tab: View?, category: MenuCategory?)
}
// call that method like this:
tabs!!.setOnTabSelectedListner(OnTabSelectedListener { tab, category ->
// ...
})
If you've not switched to Kotlin-1.4 (which is still in beta state), you have to manually instantiate the anonymous object if you are not willing to use the natively provided lambda syntax:
tabs!!.setOnTabSelectedListner(object : OnTabSelectedListener {
override fun onTabSelected(tab: View?, category: MenuCategory?) {
// ...
}
})