我收到一个错误。像这样 :
Error 1
:平台声明冲突:以下声明具有相同的 JVM 签名 (getData()Ljava/lang/Object;):
fun():我在typeErasure2中定义
fun getData():我在 typeErasure2 中定义
Error 2
:平台声明冲突:以下声明具有相同的 JVM 签名 (getData()Ljava/lang/Object;):
fun():我在typeErasure2中定义
fun getData():我在 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
关键字程序才能运行,否则会出错。谁能向我解释一下? :)
这与泛型无关。你的代码的问题是
public fun getData(): I
是“数据”的访问器。但当“数据”是公共领域时,评估者就显得多余了。所以当你这样做时:
val someValue = myObject.data
那么编译器无法判断是否应该使用访问器getData()
或者它应该直接指向该字段。
When getData
是私有的,那么编译器清楚地知道它不能使用它,所以它会直接指向该字段。
class typeErasure2<I>(name : I){
val data : I = name
fun getData() : I = data
}
fun main() {
val obj = typeErasure2<Int>(123)
println(obj.data) // <--- Ask yourself, what does this line do exactly?
}
class typeErasure2<I>(name : I){
val data : I = name
private fun getData() : I = data
}
fun main() {
val obj = typeErasure2<Int>(123)
println(obj.data) // <--- Here it is clear
// it is not the "getData" because that one is private,
// so it must be the public field "data" you are pointing to
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)