Say I've got a World class. A world can contain Sp...
# getting-started
p
Say I've got a World class. A world can contain Spheres, and a Sphere can have properties such as Colour. So on my World class I have a factory function within a companion object called defaultWorld. This returns me an instance of a World with two Colour.RED Spheres. What's the best way of taking a defaultWorld and modifying it so that, for example, one of the Sphere's is Colour.BLUE not RED ? At the moment all the attributes of Sphere are val's not vars, so I can't just do world.spheres[0].colour=Colour.BLUE. And even if I did change it to var, that changes the defaultWorld for everything. So what's the best way of having some sort of template object that I can easily create new variants from ?
🤔 1
s
It kind of depends - you could rely on mutable state and access the World members via locks or some other mutual exclusion mechanism, or maybe you could generate a new World with the spheres you need and replace the old World with this new one
how are you storing the spheres? are they just members of the class or are they in a queue or another similar structure?
k
Or maybe look into a World builder with defaults?
c
data classes have a generated
copy()
method, and you can use its named arguments to only change some of its properties on copy
b
I would use
data
class
copy
like @Casey Brooks mentioned above if the number of spheres is finite...
m
If you have a deeply nested structure of data classes, I would take a look at optics in Arrow.