kotlin - 意外覆盖 : The following declarations have th

我在这部分的 Kotlin 中遇到了错误:

class GitHubRepoAdapter(
    private val context: Context,
    private val values: List<GithubRepo>
) : ArrayAdapter<GithubRepo>(
    context, 
    R.layout.list_item,
    values
)

私有(private) val 上下文:上下文

日志中写着:

Error:(14, 25) Accidental override: The following declarations have the same JVM signature
(getContext()Landroid/content/Context;):  
    fun <get-context>(): Context  
    fun getContext(): Context!

我看不出是什么导致了问题。

最佳答案

这是因为 Kotlin 编译器试图为 val context 生成一个 getter。在您的类主构造函数中声明,即方法 getContext() , 但基类 ArrayAdapter<T> already has such a method .

您可以通过执行以下操作之一来解决此问题:

  • 将你的类的构造函数参数改为不是 val .

       class GitHubRepoAdapter(context: Context, ...
    

    这种情况下不会生成getter,冲突也就消失了。

    这似乎是您的首选解决方案,因为即使没有重新声明,there is already a synthetic property context inferred from the Java getter .

  • 使用 @JvmName 注释,apply it to the context property getter :

       class GitHubRepoAdapter(@get:JvmName("getAdapterContext") private val context: Context, ...
    

    这将使编译器生成具有另一个 JVM 名称(在注解中指定的名称)的 getter,从而避免冲突,但会使从 Java 中访问它的直观性降低(尤其是因为会有两个相似的函数)。在 Kotlin 中,您仍然可以使用原始名称 context 的属性。 .

关于kotlin - 意外覆盖 : The following declarations have the same JVM signature,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035263/

相关文章:

java - Android Studio 3.0 金丝雀 1 : Kotlin tests or

arrays - Kotlin中数据类的equals方法

javascript - Kotlin JavaScript 到 TypeScript 定义文件

android - IllegalArgumentException : Parameter spe

kotlin - 如何在 Kotlin 中向 Java 类添加静态方法

kotlin - Kotlin 中的扩展字段

gradle - 如何将 Gradle 项目中 Kotlin 的字节码版本设置为 Java 8?

android - 无法使用 Android Studio 3.0 + DataBinding +

android - Kotlin Coroutines 在 Android 中的正确方式

kotlin - 实现Java接口(interface)时如何克服 "same JVM signat