在 Kotlin 中通过委托访问委托接收器

Accessing the delegating receiver with by delegation in Kotlin

给定一个接口:

interface Countable
{
    val count: Int
}

还有一个 implementation/factory:

fun countable(counter: () -> Int): Countable = object : Countable
{
    override val count: Int
        get() = counter()
}

我可以使用 class by 委托功能来实现:

class CountableThing : Countable by countable({ 123 })

因此该代码段可预测地输出 123:

fun main()
{
    val countableThing = CountableThing()
    println(countableThing.count)
}

我的问题是,在委托 class 的上下文中,有什么方法可以获取委托接收者的实例吗?

也就是说,我的委托Countable实现(fun countable中定义的匿名对象)see/accessCountableThingclass的接收者实例可以吗? ?

我试过这个:

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

不,不能,委托对象只是对象,他们甚至不知道它们是否将用于通过委托实现接口。但是,您可以考虑使用 delegated properties 来委托属性 setter 和 getter 实现:

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,它是对 属性 被委托的对象的引用。