I'm trying to extend a class and implement an interface that are defined in a java library (AndroidX). However, when I try to implement the interface function I get a type mismatch error with my return value. Since I'm using an interface defined in the AndroidX library, simply changing the interface function signature to make it build is not an option.
I'm basically converting this other SO answer to Kotlin: https://stackoverflow.com/a/34398747/535638
I tried to generalize this error with the code below, to hopefully save you some effort in grokking the other SO question, and I'm getting the same compiler error with this generalized code.
open class LibraryClassA {
}
open class LibraryClassB {
val retval = LibraryClassA()
// this kotlin signature seems to be inferred/transcribed from java by the IDE/compiler
open fun <T : LibraryClassA?> foobar(): T? {
return null
}
}
class MyClass : LibraryClassB() {
override fun <T : LibraryClassA?> foobar(): T? {
return retval // compiler error on this line - type mismatch, Required T?, Found LibraryClassA
}
}
The other answer explains the why behind the compiler error, but since I cannot modify the library I'm using easily, the solution to my problem was to do a cast and suppress the warning.
My final code looks like this:
override fun <T : Preference?> findPreference(key: CharSequence): T? {
// unchecked cast needed since we can't modify the library code to call this with the
// correct type parameter, and we can't modify the function signature
@Suppress("UNCHECKED_CAST")
return this.preference as T
}