https://kotlinlang.org logo
#announcements
Title
# announcements

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

Alin B.

07/11/2018, 9:48 AM
What would be the right way to generate an UUID in kotlin?
a

Andreas Sinz

07/11/2018, 9:49 AM
UUID.randomUUID()
a

Alin B.

07/11/2018, 9:52 AM
I used that but it uses java.util. I thought there is something built in. Thank you
a

Andreas Sinz

07/11/2018, 9:54 AM
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

gildor

07/11/2018, 9:57 AM
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

Alin B.

07/11/2018, 9:59 AM
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

gildor

07/11/2018, 10:00 AM
Sure
a

Alin B.

07/11/2018, 10:00 AM
I am learning Kotlin and don't want to pass unneeded behavior from java
g

gildor

07/11/2018, 10:00 AM
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

Alin B.

07/11/2018, 10:02 AM
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

Andreas Sinz

07/11/2018, 10:02 AM
or even shorter
fun getUUID() = UUID.randomUUID().toString()
c

Can Orhan

07/11/2018, 10:10 AM
@Alin B. Yup! And that's a perfect example of reusing what the platform provides but making it more idiomatic
g

gildor

07/11/2018, 10:11 AM
Exactly, Kotlin doesn’t have Utils classes, because you can use much more idiomatic and convenient extensions
a

Alin B.

07/11/2018, 10:34 AM
Thank you to all for your time.
10302 Views