0

With

interface Anint {
    fun doStuff()
}

class AClass : Anint {
    override fun doStuff() = print("hello")
}

class AnintManager {
    //val l = listOf<Anint>
    fun manage() { //for each Anint, doStuff() }
}

fun main(args: Array<String>) {
    val a = AClass()
    val b = AClass()
    AnintManager().manage()
}

How can I do so that every time I instanciate a new object that implement "Anint", that object gets added to list in the "AnintManager"? It'll be cool if the code for achieving this is placed in the interface

user3491043
  • 129
  • 7
  • 2
    You would need an `Anint`-FactoryMethod for that, which creates the implementation and then registers that impl to the `Manager`. – Lino Nov 16 '17 at 11:04
  • you can make it a static list somewhere, and call a static method that adds elements to it from within the constructor – Stultuske Nov 16 '17 at 11:04
  • @Stultuske let `this` escape from constructor is said to be bad design. And can break the whole programm – Lino Nov 16 '17 at 11:06
  • @Stultuske have a look at [this](https://stackoverflow.com/a/8446036/5515060) – Lino Nov 16 '17 at 11:07
  • @Lino So I should do a method like "createAnint(anintInstance: Anint)" that returns an object implementing Anint while adding it to the list ? If so, where should it be ? In the "AnintManager" class or elsewhere? – user3491043 Nov 16 '17 at 13:52
  • That's what you have to decide, you could make a static method in `AnintManager` which returns `AClass` and registers that instance – Lino Nov 16 '17 at 14:06
  • @Lino seems good to me, thanks ;) – user3491043 Nov 16 '17 at 14:12

0 Answers0