https://kotlinlang.org logo
#announcements
Title
# announcements
i

Ifvwm

07/14/2019, 4:22 PM
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

kevinherron

07/14/2019, 4:43 PM
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

Hullaballoonatic

07/14/2019, 5:08 PM
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

gildor

07/14/2019, 11:19 PM
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

Ifvwm

07/15/2019, 2:01 PM
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

gildor

07/15/2019, 3:10 PM
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

Hullaballoonatic

07/15/2019, 3:11 PM
It's a FP approach. Kotlin supports FP.
I'd prefer the OOP way, too but 🤷
g

gildor

07/15/2019, 4:12 PM
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

Hullaballoonatic

07/15/2019, 4:14 PM
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

gildor

07/15/2019, 4:18 PM
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

Hullaballoonatic

07/15/2019, 8:15 PM
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.