Hi! In my KMP project I am struggling with the `di...
# multiplatform
c
Hi! In my KMP project I am struggling with the
diamond problem
.
Copy code
//module 1
interface CommonCore {
   
    fun doFoo(){
        foo()
    }
    
    fun foo() {
        println("foo in CommonCore")
    }
}

interface AndroidCore: CommonCore {
    override fun foo() {
        super.foo()
        println("foo in AndroidCore")
    }
}

//module 2
interface Common: CommonCore {
    override fun foo() {
        super.foo()
        println("foo in Common")
    }
}

class Android: AndroidCore, Common {
    override fun foo() {
      	super<AndroidCore>.foo() //common core will be called twice...
        super<Common>.foo()
        println("foo in Android")
    }
}


fun main() {
    Android().doFoo()
}
With this approach
CommonCore.foo()
will be called twice which of course is not ideal. What do you guys do, to avoid it?
j
Well the diamond problem is when you have multiple inheritance; but that's not the case in Kotlin, you inherit from one class, the rest is implementation of interfaces. If you have chosen to structure Android.foo() so that it calls everything and its dog, just don't call super.foo() in AndroidCore and you are fine 🙂
Either way - you have the full control here; or at least in the example you've provided...
c
Calling super.foo() is a must have, at least for me, because othervise I can lose platform specific or common implementation. So I need to call platform specific implementation and common as well, but if I do that, the CommonCore implementation will be triggered multiple times. Maybe the solution is to get rid of the Common class, and just have separate implementations on every platform (Android, IOS, Web).
j
What I meant is that you need to decide what depends on what - if it is that each PlatformCore.foo() needs to call the CommonCore.foo() because it depends on some initialization in CommonCore, then you should structure things so that Common.foo() does not call the CommonCore.foo() (ie. avoid super.foo() in Common.foo()) - because you know that it has been already called in each PlatformCore.foo(). Of course, this is assuming that you never instantiate object of type Common, and use it only to share stuff.
[But that seems given, because Common is just an interface, not a class.]
Does that make more sense? Or am I still missing some details in what you need to achieve?
Another possibility that comes to my mind - given that you call super<AndroidCore>.foo() followed by super<Common>.foo(), I even wonder if it is necessary to have the method always be called foo() - maybe it would be more correct to have foo() and bar() that are kind of orthogonal?
c
Yes it makes sense. It looks promising so far. I just need to check on a real project to be sure if it covers everything.
👍 1
But anyway, thanks. Maybe you solved my problem 😄
j
Would be great 😄