如果两个接口都实现了,您可以将两个接口委托给同一个对象。为此,只需将对象设为构造函数参数,例如:
class NowActivity(delegate: NowDelegateImpl): AppCompatActivity(),
NowScreen by delegate,
NowDelegate by delegate {
constructor (): this(NowDelegateImpl()) {} // need this default constructor for Android to call
...
}
如果委托没有实现这两个接口的所有内容,您可以将其设为成员并手动将部分功能委托给它。
class NowActivity(private val delegate: NowDelegateImpl):
AppCompatActivity(),
NowScreen,
NowDelegate by delegate {
constructor (): this(NowDelegateImpl()) {} // need this default constructor for Android to call
override fun callSomeFund() { delegate.callSomeFund() }
}
这两个选项都需要您创建一个默认构造函数,该构造函数创建用于委托的对象并将其传递给主构造函数。
这里它被分解为一个包罗万象的示例,它不是特定于 Android 的,以防其他人想看到正在发生的一切......
示例1,将所有接口委托给同一个对象:
interface CommonStuff {
fun foo1()
fun foo2()
}
interface LessCommonStuff {
fun bar()
}
class CommonDelegate1: CommonStuff, LessCommonStuff {
override fun foo1() {}
override fun foo2() {}
override fun bar() {}
}
class Activity1(delegate: CommonDelegate1):
LessCommonStuff by delegate,
CommonStuff by delegate {
constructor (): this(CommonDelegate1()) {} // need this default constructor
// ...
}
示例2,使用成员手动委托一些接口:
interface CommonStuff {
fun foo1()
fun foo2()
}
interface LessCommonStuff {
fun bar()
}
class CommonDelegate2: CommonStuff {
override fun foo1() {}
override fun foo2() {}
fun barLikeThing() {}
}
class Activity2(private val delegate: CommonDelegate2):
LessCommonStuff,
CommonStuff by delegate {
constructor (): this(CommonDelegate2()) {} // need this default constructor
override fun bar() { delegate.barLikeThing() }
}