Android 可以用一个类提供多个委托类型吗?
我想从一个类中提供多个不同类型的委托。例如:Android 可以用一个类提供多个委托类型吗?,android,kotlin,kotlin-delegate,Android,Kotlin,Kotlin Delegate,我想从一个类中提供多个不同类型的委托。例如: class A { val instanceOfB = B() val aNumber: SomeType by instanceOfB val anotherNumber: SomeOtherType by instanceOfB } class B { operator fun <T1: SomeType> getValue(thisRef: Any?, property: KProperty<T1>)
class A {
val instanceOfB = B()
val aNumber: SomeType by instanceOfB
val anotherNumber: SomeOtherType by instanceOfB
}
class B {
operator fun <T1: SomeType> getValue(thisRef: Any?, property: KProperty<T1>): T1 {
return SomeType()
}
operator fun <T2: SomeOtherType> getValue(thisRef: Any?, property: KProperty<T2>): T2 {
return SomeOtherType()
}
}
open class SomeType {}
open class SomeOtherType {}
A类{
val instanceOfB=B()
val aNumber:instanceOfB的某个类型
val anotherNumber:SomeOtherType by instanceOfB
}
B类{
运算符fun getValue(thisRef:Any?,属性:KProperty):T1{
返回SomeType()
}
运算符fun getValue(thisRef:Any?,属性:KProperty):T2{
返回SomeOtherType()
}
}
打开类SomeType{}
打开类SomeOtherType{}
此示例给出以下编译器错误:
“运算符”修饰符不适用于此函数:第二个参数的类型必须为KProperty或其超类型
是否有某种方法可以指定泛型类型参数以实现此目的?这是我编译和运行泛型类型参数的唯一方法,尽管我强烈建议不要在概念验证之外使用泛型类型参数,因为内联将生成大量垃圾代码,并且每次
getValue
调用都将在整个语句中运行,当语句:
class B {
inline operator fun <reified T : Any>getValue(thisRef: Any?, property: KProperty<*>): T {
return when(T::class.java){
SomeType::class.java -> SomeType() as T
SomeOtherType::class.java-> SomeOtherType() as T
else -> Unit as T
}
}
}
B类{
内联运算符fun getValue(thisRef:Any?,属性:KProperty):T{
返回时间(T::class.java){
SomeType::class.java->SomeType()作为T
SomeOtherType::class.java->SomeOtherType()作为T
else->单位为T
}
}
}
还有一个生成委托的操作符fun provideDelegate
,但它也被限制为1个返回值。我认为现在没有优雅的/受支持的方法来做你需要的事情。你能证明你的意思吗?它会生成大量垃圾代码?@howettl它是一个内联函数,所以整个块都被复制到调用位置。如果检查类A的字节码,您会发现生成的函数getaNumber()
和getanotherNumber()
根本没有调用instanceOfB
getValue
方法。相反,您将看到在每个getter函数中复制了整个getValue
。使用这种方法需要注意的另一件事是,如果您有多个相同类型的委托属性,则需要确保以辅助方式识别它们(例如使用property.name
)以避免归还错误的财产。