Constructors for Objects :pray:
# language-proposals
g
Constructors for Objects 🙏
11
d
Doesnt
init {}
do that?
k
I think he wants to pass params to it... which raises the question for me, how would that work? Wouldn't you have to pass the params every time you access it?
Or would you want access to be param-free and if it hasn't been inited yet, throw an exception?
d
Yeah that does not make sense
g
For what? Singletons with parameters? Sounds like a terrible antipattern that never should be added to the language
☝️ 2
n
Can you use a class and vals instead? Or a memoized function? (But beware of memory leaks)
l
Use case?
g
Yes I'd like a way to initialize with a parameter once. On Android it's a classic case to have a Singleton hold a reference to your Application class which is fine because this lives as long as your process. On other platforms I'd like to configure the singleton once and not to have to pass values as parameters to every single function.
g
On Android it’s a classic case anti-pattern
There are plenty ways to avoid it if only case is just get application/application context instance
g
Well if you pass Application, you can’t leak your Context so I don’t consider this to be such an issue. For example that’s what AndroidViewModel takes as parameter, for the same reason. It’s not going to behave in a bad way. I agree with parameters like that, it could for sure be used in a bad way just by retaining an Activity or Fragment.
g
I’m not talking about context leak only, but it also big issue for general-usage feature that should be useful not only for Android
Issue is pattern itself, when some global object without any lifecycle initialised from random place with random parameters
it’s issue even on Android, when on some versions LocalBroadcastStation leaked if you pass activity context, you can handle it, but it already shows how dangerous this approach
Just as example, if I would like to provide something like LocalBroadcastStation (which itself very questionable itself), I would just create an instance and keep it in Application class, so you could retrieve it if you have context, or made something like singleton where application sets context after onCreate and throw an exception if someone would try to use it before app initialization, even infamous context initialization using ContentProvider is better than that And for my own code I would just use dependency injection instead, without any explicit global state My point that use case is super narrow (singleton that requires some god object) and you have better alternatives I really would like to see any use case if you think it’s beneficial
l
@galex For that application context thing, I made small a library for that: https://github.com/LouisCAD/Splitties/blob/master/modules/appctx/README.md