# Interfaces Implementation by delegation, solving the diamond problem

Hi is there a way to solve the diamond problem with delegation? getting crazy trying different solutions and can’t find a way to have the last object to behave properly: Here’s my test code:

``````interface C {
var a: Int
}

class Ci : C {
override var a: Int = 1
}

interface A: C {
//var a: Int
val f: String
}

interface B: C {
//var a: Int
val g: String
}

class Ai(ci: Ci = Ci()): A, C by ci {
override val f: String = "class A"
}

class Bi(ci: Ci = Ci()): B, C by ci {
override val g: String = "class B"
}

class Xi(val ci: Ci = Ci(), val ai: Ai = Ai(ci), val bi: Bi = Bi(ci)): C by ci, A by ai, B by bi {
val h: String = "class X"
override var a = ci.a
}

fun main() {
val a = Ai()
val b = Bi()
println(a.f)
println(b.g)
val x = Xi()
println("\${x.a} \${x.ci.a} \${x.ai.a} \${x.bi.a}")
x.a = 2
println("\${x.a} \${x.ci.a} \${x.ai.a} \${x.bi.a}")
x.ci.a = 3
println("\${x.a} \${x.ci.a} \${x.ai.a} \${x.bi.a}")
x.ai.a = 4
println("\${x.a} \${x.ci.a} \${x.ai.a} \${x.bi.a}")
x.bi.a = 5
println("\${x.a} \${x.ci.a} \${x.ai.a} \${x.bi.a}")
}
``````

it prints the following:
class A
class B
1 1 1 1
2 1 1 1
2 3 3 3
2 4 4 4
2 5 5 5
In C/C++ what I would try to do is to have a reference pointing to ci.a but in kotlin i dunno what to do. Also is pretty stupid it says “Class ‘Xi’ must override public open var a: Int defined in Xi because it inherits many implementations of it” because it’s clearly the same object.

Ok, I see that if I do the trasformation

``````data class Box(var value: Int)

interface C {
var box: Box
}
``````

it works, still I find it a bit terrible overall. If I give x.a = Box(3) doesn’t work anymore as I would need,
so I should do a setter like: `set(value) = { a = value; ci.a = value }` which is quite horrible anyway.

Is there any way to make var a in class Xi ‘TO BE (AS SAME OBJECT IN MEMORY)’ ci.a?

You could use

``````override var a
get() = ci.a
set(value) { ci.a = value }
``````