jeudi 26 mars 2020

How do you resolve circular imports in Kotlin

I'm new to programming in Kotlin and I've already managed to run into the classic circular dependency issue - I know Kotlin can cope with those but I'd like to know how would I go about changing my design to avoid it. What structures or Kotlin functionality should I use in the following?

import myClass

interface myInterface {
    fun useMyClass(myInstance: myClass)
}
import myInterface

class myClass(myList: List<myInterface>) {
    val storedList: List<myInterface> = myList
    var myValue: Int = 10
}

I would like myClass to store multiple objects which implement myInterface, but I would also like each of those objects to reference the class they have been passed to, i.e. each call of useMyClass would have the signature of useMyClass(this).

For example, I could create a class

class implementingMyInterfaceClass(): myInterface {
    override fun useMyClass(myInstance: myClass) {
         myInstance.myValue += 10
    }
}

and call it somewhere within myClass:

implementingMyInterfaceClass().useMyClass(this)

Technically I could create another construct in the middle which would be used by myInterface and inherited/implemented by myClass, but this just doesn't feel correct. Any suggestions?

Aucun commentaire:

Enregistrer un commentaire