我是 Kotlin 的初学者,我正在尝试使用以下代码制作一个基本的 person 类:
class Person(_firstName: String, _lastName: String, _age: Int){
val firstName: String = _firstName
val lastName: String = _lastName
var age: Int = _age
fun setAge(newAge: Int){
age = newAge
}
}
我想在我的类中添加一些基本方法,例如 getter 和 setter。当我创建 setAge 函数并尝试编译时,出现以下错误:
Error:(4, 5) Kotlin: Platform declaration clash: The following declarations have the same JVM signature (setAge(I)V):
fun <set-age>(<set-?>: Int): Unit defined in Person
fun setAge(newAge: Int): Unit defined in Person
Error:(6, 5) Kotlin: Platform declaration clash: The following declarations have the same JVM signature (setAge(I)V):
fun <set-age>(<set-?>: Int): Unit defined in Person
fun setAge(newAge: Int): Unit defined in Person
我是 Kotlin 的新手,完全不知道问题是什么。我在 Java 方面有一些经验,并且从未真正遇到过创建(几乎)像这样微不足道的类的任何问题。
有人可以以初学者友好的方式解释这里到底是什么问题,以及我可以做些什么来解决这个问题/将来避免它。谢谢你。
最佳答案
这里的问题是
fun setAge(newAge: Int){
age = newAge
}
当你声明
var age: Int = _age
它将生成
setAge
为您提供的方法,因此您应该做的是覆盖 age
的 setter .但是,在您的情况下,这不是必需的,因为生成的 setter 将与您的 setAge
执行相同的操作。方法。也可以引用official documentation了解更多。
关于java - Kotlin:平台声明冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59920597/