What would be the right way to generate an UUID in kotlin?

Question

What is the recommended way to generate UUID in Kotlin?

Answer

The recommended way to generate UUID in Kotlin is to use `UUID.randomUUID()` method from `java.util.UUID` library. This is because Kotlin reuses everything from Java where it's applicable and only adds stuff on top of it where it's needed. It's also advised to follow Kotlin's philosophy and reuse idiomatic APIs instead of creating Utils classes. For example, a more idiomatic implementation would be `fun getUUID() = UUID.randomUUID().toString()`.

a
What would be the right way to generate an UUID in kotlin?
a
UUID.randomUUID()
a
I used that but it uses java.util. I thought there is something built in. Thank you
a
Rule of thumb is, that kotlin reuses everything from java where its applicable and only adds stuff on top of it where its needed
1
👍 1
g
It’s philosophy of Kotlin: Reuse everything what is available on the platform and add more idiomatic API for that if it’s required. Allows to have small stdlib and close to zero overhead
👍 1
a
So in this case, if I want to use this around my code, is it ok to have a file Utils in which have
Copy code
`fun getUUID(): String {
    return UUID.randomUUID().toString()
}`
g
Sure
a
I am learning Kotlin and don't want to pass unneeded behavior from java
g
but I would rename it to something like randomUUID() or randomUUIDString()
Why? 🙂
Would it be something differrent if kotlin would provide
kotlin.util.UUID
class? The only difference practically would be just diffrent import, you now have
jva.util.UUID
Good interop with platform is one of the strongest sides of Kotlin
a
I mean there are things done different in Kotlin and some things that are done in Java don't need to be made in Kotlin. For instance instead of StringUtils have fun directly in
String.toUpperCase
a
or even shorter
fun getUUID() = UUID.randomUUID().toString()
c
@Alin B. Yup! And that's a perfect example of reusing what the platform provides but making it more idiomatic
g
Exactly, Kotlin doesn’t have Utils classes, because you can use much more idiomatic and convenient extensions
a
Thank you to all for your time.
11256 Views