gpt4 book ai didi

android - 是否可以为单个类提供多种委托(delegate)类型?

转载 作者:行者123 更新时间:2023-11-29 23:49:19 25 4
gpt4 key购买 nike

我想从一个类中提供多个不同类型的不同委托(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>): T1 {
return SomeType()
}

operator fun <T2: SomeOtherType> getValue(thisRef: Any?, property: KProperty<T2>): T2 {
return SomeOtherType()
}
}

open class SomeType {}
open class SomeOtherType {}

此示例给出了以下编译器错误: 'operator' modifier is inapplicable on this function: second parameter must be of type KProperty<*> or its supertype

有没有什么方法可以指定泛型类型参数,这样我就可以实现这一点?

最佳答案

这是我编译和运行它的唯一方法,尽管我强烈建议除了概念验证之外不要使用它,因为内联会生成大量垃圾代码,并且每个 getValue 调用都将运行整个过程when 语句:

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
}
}
}

还有 operator fun provideDelegate 生成委托(delegate),但它也仅限于 1 个返回值。我不认为有优雅/支持的方式来做你现在需要的事情。

关于android - 是否可以为单个类提供多种委托(delegate)类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51072178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com