gpt4 book ai didi

intellij-idea - "same JVM signature"实现包含 getter 方法的 kotlin 接口(interface)

转载 作者:行者123 更新时间:2023-12-02 12:47:16 26 4
gpt4 key购买 nike

interface MyInterface {
fun getTheString(): String
}
class MyClass(var theString: String) : MyInterface {
...
}

通常,当我在类的构造函数中有一个变量时,它会为该变量创建一个 getter 和 setter。在 MyClass 中,getTheString()setTheString(String) 方法在未实现 MyInterface 时存在。

MyClass 实现 MyInterface 时,出现错误:

意外覆盖:以下声明具有相同的 JVM 签名 (getTheString()Ljava/lang/String;):

  • public final fun(): String defined in MyClass
  • public abstract fun getTheString(): String defined in MyClass

我也有错误:“MyClass”类不是抽象的,也没有实现抽象成员 public abstract fun getTheString(): String defined in MyInterface.

所以我有几个问题:

  1. 为什么在实现接口(interface)时使用相同的 JVM 签名生成 2 个 getter 方法,而在没有实现接口(interface)的情况下生成一个 getter 方法?
  2. 为什么kotlin会自动生成getTheString()方法,却提示我没有实现?
  3. 如何让变量生成的getter成为接口(interface)中方法的实现?

最佳答案

如果接口(interface)确实是 Kotlin 的,并且你可以更改它,它应该是

interface MyInterface {
val theString: String
}

首先。 Java 仍会看到 getTheString(),但在 Kotlin 中实现和使用会更好。

否则一个好的选择是

class MyClass(@set:JvmName("setTheString") var _theString: String) : MyInterface {
override fun getTheString() = _theString
}

不幸的是,它仍然有一个重复的 getter,您不能只将 getter 设为私有(private)。或者

class MyClass(private var _theString: String) : MyInterface {
override fun getTheString() = _theString
fun setTheString(value: String) {
_theString = value
}
}

请注意,如果接口(interface)是在 Java 中,getTheString() 将作为属性对 Kotlin 可见。

查看问题 https://youtrack.jetbrains.com/issue/KT-6653https://youtrack.jetbrains.com/issue/KT-19444在 Kotlin 错误跟踪器上。

关于intellij-idea - "same JVM signature"实现包含 getter 方法的 kotlin 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55458609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com