how I can store the instances into a global list w...
# announcements
i
how I can store the instances into a global list when the classes instantiate? in python it’s like alist = [] class T: def __init__(self): alist.append(self) then I can get all the instances of class T in alist
k
make a
companion object
and put the list in there?
this will leak unless you figure out how/when to remove the objects from the list when you don’t need them any more
i guess you could use `WeakReference`… not sure what you’re up to here
h
almost perfectly synonymous to your python code (just that you must declare a type for your list):
Copy code
val allFoos = mutableListOf<Foo>()

class Foo {
    init {
        allFoos += this
    }
}
g
Just really curious, What is your use case for this? In general it's usually concider as bad style to introduce implicit global state
i
this case in python is used to handle websocket, every new coming client will store to a global list, so we can send message to all the client
g
Why do this on object creation? Usually better to have some class that returns connection object, so everything will be handled explicitly and would require any global state, you can have multiple connections and different sets of clients and separation of concerrns in general
h
It's a FP approach. Kotlin supports FP.
I'd prefer the OOP way, too but 🤷
g
How is that FP approach? This is implicit side effect, I would say this is against of multiple paradigms of FP: not pure, side effect, global state, mutability
h
fair enough. sometimes i think of the FP approach as simply: Do what immediately works with the least headspace given to lateral concerns.
maybe we can instead call this the greedy approach
g
It's interesting point of view, but I would say this is FP 😃
Anyway, I don't think that approach where some code mabages connections and connection is created and registered is somehow more difficult, it looks for me just more correct (more testable, less connections between the program components, potentially more flexible)
h
yeah, I like to think of OOP as the coding paradigm in which programmers spend a lot of time writing code now to save time writing code later.