提供一个界面:
interface Countable
{
val count: Int
}
还有一个实现/工厂:
fun countable(counter: () -> Int): Countable = object : Countable
{
override val count: Int
get() = counter()
}
我可以使用类by
委派功能来实现此目的:
class CountableThing : Countable by countable({ 123 })
因此该代码段可预测地输出123
:
fun main()
{
val countableThing = CountableThing()
println(countableThing.count)
}
我的问题是,在委托类的上下文中,有什么方法可以获取委托接收者的实例?
换句话说,我的委托Countable
实现(在fun countable
中定义的匿名对象)可以查看/访问CountableThing
类的接收者实例吗?
我尝试过:
fun <T> countable(receiver: T, counter: () -> Int): Countable = object : Countable
{
// ...
}
class CountableThing : Countable by countable<CountableThing>(this, { 123 })
但这是无效的,因为可以预料到:
class CountableThing : Countable by countable<CountableThing>(this, { 123 })
/^^^^
'this' is not defined in this context
答案 0 :(得分:2)
不行,委托对象只是它们甚至不知道是否将用于通过委托实现接口的对象。但是,您可以考虑使用delegated properties,这些委托用于委派属性设置器和获取器的实现:
class Example {
var p: String by Delegate()
}
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name}' in $thisRef.")
}
}
然后您就可以使用
val e = Example()
println(e.p)
打印:
Example@33a17727, thank you for delegating ‘p’ to me!
如您所见,在委托实现中,可以使用thisRef
,它是对对象的引用,该对象的属性被委托。