Generate a UUID in Kotlin
Kotlin is a statically typed, modern, and expressive programming language that runs on the Java Virtual Machine (JVM) and is fully interoperable with Java.
Developed by JetBrains and officially released in 2016, Kotlin aims to address various limitations and challenges posed by other programming languages while providing a more concise and safer syntax.
How to Generate a UUID in Kotlin
Kotlin's standard library doesn't include a dedicated UUID generation function. However, since Kotlin is fully
interoperable with Java, we can use Java's java.util.UUID class to generate UUIDs in Kotlin code
seamlessly.
import java.util.UUID;fun main() {// Generate a random UUIDval myUuid = UUID.randomUUID()val myUuidAsString = myUuid.toString()// Print the UUIDprintln("Generated UUID: $myUuid")}
Explanation
- On line #1, we import the
UUIDclass. This class is part of the standard Java JDK. No 3rd party libraries are required. - On line #5, the
UUIDclass' static method,randomUUID(), is used to generate a new, version 4 UUID. The generated UUID object is stored in the variable,myUuid. - Line #6 converts the
myUuidobject into a Java String by calling itstoString()method. The String representation of aUUIDlooks like a standard UUID (i.e. d52a4216-0acc-43d7-ba00-d3ffdeecc59b). If you're going to store the UUID in a file, database or model property, or send it via an API call to a different application, you'll almost always need the String representation of themyUuidobject, rather than themyUuidobject itself. - Line #9 outputs the value of
myUuidAsStringand will look something like:Generated UUID: d52a4216-0acc-43d7-ba00-d3ffdeecc59b
Convert from a String to a UUID in Kotlin
Although it's rare, in some circumstances you might need to convert from a String representation of a UUID (like the
one from line #6 above) back into an instance of Java's UUID.
In Kotlin, you again use Java's UUID class, which provides for this scenario with the static method,
fromString(String).
Here's a short example in Kotlin:
import java.util.UUID;fun main() {// Generate a random UUIDval myUuid = UUID.randomUUID()val myUuidAsString = myUuid.toString()// Assert the UUIDs are equalval sameUuid = UUID.fromString(myUuidAsString)assertTrue { sameUuid == myUuid }}
Explanation
- Line #9 shows converting the string representation of a UUID into a Java
UUIDinstance (sameUuid) using thefromString(String)method. - Line #10 is included to show that the 2
UUIDinstances are equal.
How can we improve this page? Let us know!