Skip to content
DeveloperMemos

Creating a UUID in Kotlin

Kotlin, UUID1 min read

Universally Unique Identifiers (UUIDs) are commonly used to uniquely identify entities or resources in software systems. A UUID is a 128-bit value represented as a sequence of characters. In Kotlin, generating a UUID is straightforward and can be achieved using the java.util.UUID class.

Generating a Random UUID

The simplest way to create a UUID in Kotlin is by generating a random UUID. The UUID class provides a static randomUUID() method, which returns a new randomly generated UUID. Here's an example:

1import java.util.UUID
2
3fun main() {
4 val uuid = UUID.randomUUID()
5 println(uuid.toString())
6}

The randomUUID() method generates a new UUID each time it is called. Running the code snippet above will output a randomly generated UUID.

Creating a UUID from a String

Sometimes, you may need to create a UUID from a given string representation. The UUID class also provides a constructor that accepts a string parameter representing the UUID. Here's an example:

1import java.util.UUID
2
3fun main() {
4 val uuidString = "550e8400-e29b-41d4-a716-446655440000"
5 val uuid = UUID.fromString(uuidString)
6 println(uuid.toString())
7}

In the code snippet above, we create a UUID by passing the string representation to the UUID.fromString() method. The fromString() method parses the string and returns a corresponding UUID object.

Working with UUIDs in Android

In Android development, UUIDs can be used for various purposes such as generating unique identifiers for database records or as identifiers for Bluetooth devices. Here's an example of generating a UUID for an Android application. Please keep in mind that the code below is actually NOT RECOMMENDED for generating user IDs - it is just included for the sake of an example.

1import java.util.UUID
2
3fun generateDeviceId(): String {
4 val androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
5 val uuid = UUID(androidId.hashCode().toLong(), Build.SERIAL.hashCode().toLong())
6 return uuid.toString()
7}

In the code snippet above, we generate a device ID by combining the Android ID and device serial number. The resulting UUID is returned as a string. Let me repeat it again just in case, DO NOT actually use the above code to generate user IDs in your app it is NOT RECOMMENDED.

Conclusion

In this article, we explored how to create UUIDs in Kotlin. We covered generating a random UUID and creating a UUID from a string representation. Additionally, we saw an example of using UUIDs in an Android application. UUIDs are useful for generating unique identifiers and can be applied to various scenarios in software development.