在 Kotlin 中获取参数化类型的参数
Get a parameter of a parametrized type in Kotlin
所以我有一个 class 具有通用类型
class GenericClass<T> {
// At some point in the class I have variable item of type T
val name: String = item.name
}
我确信 GenericClass 的类型 T 将与具有“名称”属性 的 class 一起使用。但当然在这一行我得到了一个“未解析的参考名称”。 Android Studio 通过“创建扩展 属性 T.name”为我生成了这段代码“=13=]
private val <T> T.name: String
get() {}
我真的不知道get之后在括号{}里放什么。我尝试了 return name
,但出现递归 属性 错误。
有什么想法吗?
谢谢
如果你知道每个类型 T 都有 属性 name
你可以隐式声明它:
// GenericClass.kt
class GenericClass<T : HasName> {
// At some point in the class I have variable item of type T
val name: String = item.name
}
// HasName.kt
// Create new interface with "name" property
interface HasName {
val name: String
}
但是您还必须为所有可以用作 T 的 类 实现这个新接口。
I know for sure that the type T of GenericClass will be used with a class that has the "name" property.
然后你需要明确声明。默认情况下,T
扩展 Any?
。您需要通过声明一些接口来缩小可能的 T
类型,例如
interface Named {
val name : String
}
并将 T : Named
作为通用参数传递。您还需要制作所有 classes,您将作为通用参数传递,以实现该接口。顺便说一句,GenericClass<T : Named>
class 本身可以声明为实现该接口:
class GenericClass<T : Named> : Named {
override val name: String = item.name
}
所以我有一个 class 具有通用类型
class GenericClass<T> {
// At some point in the class I have variable item of type T
val name: String = item.name
}
我确信 GenericClass 的类型 T 将与具有“名称”属性 的 class 一起使用。但当然在这一行我得到了一个“未解析的参考名称”。 Android Studio 通过“创建扩展 属性 T.name”为我生成了这段代码“=13=]
private val <T> T.name: String
get() {}
我真的不知道get之后在括号{}里放什么。我尝试了 return name
,但出现递归 属性 错误。
有什么想法吗?
谢谢
如果你知道每个类型 T 都有 属性 name
你可以隐式声明它:
// GenericClass.kt
class GenericClass<T : HasName> {
// At some point in the class I have variable item of type T
val name: String = item.name
}
// HasName.kt
// Create new interface with "name" property
interface HasName {
val name: String
}
但是您还必须为所有可以用作 T 的 类 实现这个新接口。
I know for sure that the type T of GenericClass will be used with a class that has the "name" property.
然后你需要明确声明。默认情况下,T
扩展 Any?
。您需要通过声明一些接口来缩小可能的 T
类型,例如
interface Named {
val name : String
}
并将 T : Named
作为通用参数传递。您还需要制作所有 classes,您将作为通用参数传递,以实现该接口。顺便说一句,GenericClass<T : Named>
class 本身可以声明为实现该接口:
class GenericClass<T : Named> : Named {
override val name: String = item.name
}