Does kotlin have any way to generate random unique...
# announcements
a
Does kotlin have any way to generate random unique id in compile time. I mean id is random, but is const for runtime? So i can write compiler plugin, but may be community already has solution. For example: // sourse fun a(): String = CompileTimeId.nextId() // compiled code fun a(): String = "hdhdjdnwld"
c
hmm. Maybe you could hash your jar (if you're building for JVM)?
a
I can't i need more than one id with that logic.
s
Does it have to be constant between runs?
c
You could use Random() and seed it with a hash of the jar.
a
It must be constant in one run. Can be different between runs.
c
actually I'd seed it with the git sha of your latest commit, inject that with an environment variable (assuming you're building with git on a CI system)
s
then just generate a UUID at startup
a
I think i cant use random. Because if i call multiple times function a (see example below) result will be different.
s
just call it once and cache the result
a
Its so problematic to cache result. Exaclty by that reason i need const in compile time.
s
it's really not
at startup, generate your UUID, and then just use that
a
Ok. Some more real example of usage. I cant modify constructor and i really dont like to use singleton in this case. class A { val id = CompileTimeId() }
c
val id = IdGenerator().getFirstId()
class IdGenerator { val rng = Random(System.env("GIT_SHA")) val firstId = rng.next() val secondId = rng.next() }
don't actually know how seeding works but maybe you get the idea?
a
Ок. Add another class B with simular logic. B().id == A().id?
I think ids will be same. Its not unique.
c
if they use the same seed, and id is called in the same order, yes
class B { val rng = Random(System.env("GIT_SHA") + "classb") } class A { val rng = Random(System.env("GIT_SHA") + "classa") }
now they'll be different
a
Yes. But now we have unique strings. classa and classb. In that case i can write ids by hands.
c
the id would still be generated by rng.next()
a
Yes. Its no difference between 'classa' and 'result_from_random' because its unique.
c
a
Thank you. Its can be works.
👍 1
348 Views