Delegate Interface with current class

Is it possible to do something like:

abstract class A
interface B
class C(val a: A) : B
class D : A, B by C(this)

Or something similar? If the design is bad, that’s a whole other thing, but I feel like this should make sense. Is there a better way to do this kind of thing?

1 Like

Sadly, that’s not possible because you don’t have access to this in the class header. The only way to do it right now is like this:

abstract class A
interface B
class C : B{
    lateinit var a: A
}
class D(c: C = C()) : A(), B by c {
    init{
        c.a = this
    }
}
fun main(){
    println(D().toString())
}

or this if you don’t want to allow any caller to change the implementation of C:

abstract class A
interface B
class C : B{
    lateinit var a: A
}
class D private constructor(c: C) : A(), B by c{
    constructor(): this(C()){}
    init{
        c.a = this
    }
}