I've an `object ` that is quite useful to access s...
# announcements
c
I've an
object
that is quite useful to access statically and dynamically. It has some nested properties and classes, and I am currently serializing it with kotlinx.serialization to save it when the application closes. However for loading, Kotlin does not allow me to assign the object with =, is there a way to assign it anyway or another way to do this? The object again has nested objects inside it, so manually setting each property is a solution I would rather avoid 🙂
n
Why doesn't Kotlin let you assign? Did you initialize with val?
c
I'm using the object keyword, the error the ide shows me is that val can't be re-assigned yeah
I don't actually use the
val
keyword though
f
As i understood good You can fill in the nested object before you save it, so that afterwards when you load (deserialize) it it's filled in.
n
When you declare an object directly then it's like a val
My first thought would be that if you are serializing and deserializing application data, I wouldn't want to make that a global
You want to be explicit on what depends on it, IMHO
c
It's a "Settings" object for preferences, it's nice that I can declare different categories and access them in a type safe way by nesting objects. I could pass this around everywhere in the frontend, but it's hard to predict when I will need it. Since settings will actually have their own properties instead of String keys, it is actually a lot easier to know where settings are used, and the structure for declaring it this way is very nice, with default values and possible values near each other with low boilerplate. The same thing could be achieved with regular class syntax, but I think it'd be really ugly and harder to read 😞 unless any of you have an idea for another way? I may end up just using reflection to set it anyway, but definitely want to hear other ideas first
it has the same purpose of a yaml config or similar but in a nice kotlin type safe way
n
Not really sure I fully understand what you mean
But I would say still there no real justification for using globals here than I can see
You can have a top level Settings class,.and then optionally you could group related settings into other settings classes, e.g. EditorSettings, VisualSettings, and have Settings contain instances of those
And then whoever needs it, asks for it in their signature, and you pass it,.same as anything else
If you make it a global then usage of it will start to creep up everywhere, making things harder to test. If anything in it is mutable then that would be especially bad (and presumably people might want to change settings)
s
If you are using a dependency injection library you can make it a normal class and declare it as a singleton in the DI library and inject it into any classes that need it. This should allow you to both have a singleton Settings and allow you to easily test your code.