is it possible to copy a `Random` instance? or do ...
# announcements
c
is it possible to copy a
Random
instance? or do i have to store the seed and create it from that again?
e
Why would you want that? a)
Random
is itself thread-safe, so you can call the same instance from any number of threads; b) Creating a
Random
instance from seed is actually the same as copying an existing instance.
a
b) if you've taken no values from it
c
i want to make my random values reproducable, and i want to do that by injecting a random instance instead of injecting the seed
a
what do you use to inject?
e.g. in Koin,
Copy code
factory { Random(1234) }
Would always inject a random with same seed,
1234
c
i have this library that fills data classes with random data and i want to make the seed configurable. but i thought its nicer to inject the whole random generator instead of just the seed. https://github.com/christophsturm/randolf/blob/inject-random/src/test/kotlin/randolf/RandolfTest.kt#L196
a
woah, how did I guess your seed?!
😆 1
ok, almost looks like you're doing your own DI and all you can cope with is singletons
imagine this:
Copy code
RandolfConfig(random = { Random(1234) })
That is, random is of type:
() -> Random
i.e. a factory. It creates a new random on demand. Therefore, no actual
Random
instance exists on your config.
Which is exactly how koin example works:``` factory { Random(1234) } ```
c
thats not what i want because that would not be random at all 🙂
a
what?!
c
if i regenerate the random generator anytime i need a random i will always get the same number
a
Copy code
val oneTimeSeed = Random().next()
RandolfConfig(random = { Random(oneTimeSeed) })
c
right then i can just store the seed instead of the random in the config and thats also a fix
a
yes, true
c
thanks for your thoughts!
a
Random supports
Serializable
so if you really wanted to copy it, you can serialize and deserialize.
i
Random supports
Serializable
not yet, if we're talking about Kotlin's Random
c
basically it boils down to this: things that are not immutable should have a copy constructor