Kotlin-类型与通用返回类型和子类不匹配

杰夫:

希望大家在这场大流行中都能保持健康:)

TIA,我可以借助一些帮助找出我在做什么错!另外,我对Kotlin还是陌生的,如果这是一个愚蠢的问题,对不起。

我正在尝试扩展类并实现在Java库(AndroidX)中​​定义的接口。但是,当我尝试实现接口功能时,返回值出现类型不匹配错误。由于我使用的是AndroidX库中定义的接口,因此仅更改接口函数签名以使其构建就不是一种选择。

我基本上是将另一个SO答案转换为Kotlin:https : //stackoverflow.com/a/34398747/535638

开发者机器/ IDE信息:Android Studio 3.6.1 Build#AI-192.7142.36.36.6241897,建于2020年2月26日运行时版本:1.8.0_212-release-1586-b04 amd64 VM:JetBrains的OpenJDK 64位服务器VM sro Windows 8.1 6.3 GC:ParNew,ConcurrentMarkSweep内存:1237M内核:8注册表:ide.new.welcome.screen.force = true非捆绑插件:org.jetbrains.kotlin,com.google.services.firebase

我试图通过下面的代码来概括该错误,以期节省您处理另一个SO问题的精力,并且通过该概括的代码我也遇到了相同的编译器错误。

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
    }
}
杰夫:

另一个答案解释了编译器错误的原因,但是由于我无法轻松修改正在使用的库,因此解决我的问题的方法是进行强制转换并禁止显示警告。

我的最终代码如下所示:

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
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章