我对Kotlin中的仿制药有疑问 [英] I have a question about generic in kotlin
问题描述
我遇到一个错误.像这样:
I got an error. Like this :
Error 1
:平台声明冲突:以下声明具有相同的JVM签名(getData()Ljava/lang/Object;):
fun():我在typeErasure2中定义
fun getData():我在typeErasure2中定义了
Error 1
: Platform declaration clash: The following declarations have the same JVM signature (getData()Ljava/lang/Object;):
fun (): I defined in typeErasure2
fun getData(): I defined in typeErasure2
Error 2
:平台声明冲突:以下声明具有相同的JVM签名(getData()Ljava/lang/Object;):
fun():我在typeErasure2中定义
fun getData():我在typeErasure2中定义了
Error 2
: Platform declaration clash: The following declarations have the same JVM signature (getData()Ljava/lang/Object;):
fun (): I defined in typeErasure2
fun getData(): I defined in typeErasure2
fun main(args : Array<String>){
var te = typeErasure("Jennie")
println(te.getData())
var te2 = typeErasure2("Sam")
println(te2.getData())
}
class typeErasure<I>(name : I){
private val data : I = name
fun getData() : I = data
}
class typeErasure2<I>(name : I){
val data : I = name // error 1
fun getData() : I = data // error 2
}
当我使用private
关键字时,程序可以运行,否则会出现错误.有人可以向我解释吗? :)
when I use the private
keyword the program can run, otherwise it will get an error. anyone can explain to me? :)
推荐答案
Kotlin的属性逻辑与Java字段略有不同.
Kotlin's logic of properties differ slightly from Java's fields.
无论何时在类中声明任何变量,它的getter和setter都会自动生成,并且可以在其后用get()
或set {}
进行自定义.
Whenever you declare any variable in class, its getter and setters are automatically generated, and they can be customized with get()
or set {}
after it.
手动声明getVariable()
会导致平台冲突,因为已经在变量声明中为该字段定义了getter,并且您还将创建具有相同名称的函数.
Declaring getVariable()
manually will result in platform clash, as getter is already defined for the field in the variable declaration and you are creating function with the same name as well.
您可以使用 @JvmField 批注,指示编译器不要为该字段生成任何getter或setter.
You can use @JvmField annotation to instruct the compiler to not generate any getter or setter for the field.
@JvmField
val data: I = name
fun getData(): I = data
这篇关于我对Kotlin中的仿制药有疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!