我遇到了一个问题,希望您能就此提出反馈,尤其是在如何正确处理以下情况方面:
我有一个定义委托的抽象类:
abstract class Delegate<T: Any> {
abstract fun bindData(item: T?)
}
然后我有2个实现此委托的方法:
class DelegateForObjectA: Delegate<A>() {
var data: A? = null
override fun bindData(item: A?){
data = item
}
}
class DelegateForObjectB: Delegate<B>() {
var data: B? = null
override fun bindData(item: B?) {
data = item
}
}
我希望能够即时在这两个代表之间切换,这意味着在我的活动中,我有:
lateinit var delegate: ActionButtonsViewDelegate<*>
private var delegateA by lazy { DelegateForObjectA() }
private var delegateB by lazy { DelegateForObjectB() }
init {
delegate = delegateA
}
再后来:
fun SwitchDelegateAndBindData(item: Any?) {
if (item is B) {
delegate = delegateB
} else {
delegate = delegateA
}
delegate.bindData(item)
}
我尝试通过输入/输出实现此目标,但没有成功!如何声明我的委托属性以接受两个委托而类型没有冲突?
答案 0 :(得分:0)
尽管我不确定它为什么能工作以及它是否真的满足您的需求,但我找到了使其工作的方法^^'
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
val a = A()
val b = B()
val test = Test()
test.switchDelegate(a)
test.switchDelegate(b)
test.switchDelegate(a)
}
class Test {
var delegate: Delegate<*>
private val delegateA by lazy { DelegateForObjectA() }
private val delegateB by lazy { DelegateForObjectB() }
init {
delegate = delegateA
}
fun switchDelegate(item: Any) {
if (item is B) {
delegate = delegateB
} else {
delegate = delegateA
}
delegate.bindData( item )
}
}
abstract class Delegate<T> {
abstract fun <T:Any> bindData(item : T)
}
class A {}
class B {}
class DelegateForObjectA: Delegate<A>() {
override fun <A:Any> bindData(item: A){
println( "Binding A" )
}
}
class DelegateForObjectB: Delegate<B>() {
override fun <B:Any> bindData(item: B) {
println( "Binding B" )
}
}