Kotlin Help

UUIDs

The Uuid class represents Universally Unique Identifiers (UUIDs), also known as Globally Unique Identifiers (GUIDs).

A Uuid is a 128-bit value used to uniquely identify an entity without relying on a central system that assigns IDs. This makes UUIDs useful in distributed applications, databases, client-generated records, or Kotlin Multiplatform applications.

Use the Uuid class to work with UUID values. Unlike plain strings, a dedicated UUID type makes your code more explicit and prevents accidental use of invalid values.

To use UUIDs in your project, import the Uuid class from the kotlin.uuid package:

import kotlin.uuid.Uuid

Generate UUIDs

To generate a random version 4 UUID for regular identifiers, such as user or database IDs, use the Uuid.random() function:

import kotlin.uuid.Uuid fun main() { //sampleStart val id = Uuid.random() println(id) //sampleEnd }

You can also generate specific versions of UUIDs with the following Experimental functions:

  • The Uuid.generateV4() function generates the same type of UUID as the Uuid.random() function but explicitly states that the value is a version 4 UUID.

  • The Uuid.generateV7() function generates a version 7 UUID with a timestamp that you can use for UUID sorting.

  • The Uuid.generateV7NonMonotonicAt() function generates a version 7 UUID for a specific moment in time.

These UUID generation functions are Experimental. To opt in, use the @OptIn(ExperimentalUuidApi::class) annotation or add the following compiler option to your build file:

kotlin { compilerOptions { freeCompilerArgs.add("-opt-in=kotlin.uuid.ExperimentalUuidApi") } }
<build> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <configuration> <args> <arg>-opt-in=kotlin.uuid.ExperimentalUuidApi</arg> </args> </configuration> </plugin> </plugins> </build>

Here's an example that generates version-specific UUIDs:

import kotlin.time.Instant import kotlin.time.ExperimentalTime import kotlin.uuid.Uuid @OptIn(kotlin.uuid.ExperimentalUuidApi::class, ExperimentalTime::class) fun main() { // Generates a version 4 UUID val idVersion4 = Uuid.generateV4() println(idVersion4) // Generates a version 7 UUID val idVersion7 = Uuid.generateV7() println(idVersion7) // Generates a version 7 UUID for the specified timestamp val timestamp = Instant.fromEpochMilliseconds(1757440583000L) val idVersion7SpecificTime = Uuid.generateV7NonMonotonicAt(timestamp) println(idVersion7SpecificTime) }

Parse UUIDs

UUID values are often represented as strings, such as in URL parameters or database records.

To convert a String value to a Uuid value, use the Uuid.parse() function:

import kotlin.uuid.Uuid fun main() { //sampleStart val id = Uuid.parse("de2bc56c-ea73-4f3c-8a37-5a46fdb2d79a") println(id) //sampleEnd }

The Uuid.parse() function accepts both the standard hex-and-dash format and the hexadecimal format without dashes.

If the input is invalid, the Uuid.parse() function throws an IllegalArgumentException:

import kotlin.uuid.Uuid fun main() { //sampleStart val id = Uuid.parse("10") println(id) //sampleEnd }

If your application accepts only one representation, use the format-specific functions:

For example:

import kotlin.uuid.Uuid fun main() { //sampleStart val standard = Uuid.parseHexDash("de2bc56c-ea73-4f3c-8a37-5a46fdb2d79a") val compact = Uuid.parseHex("de2bc56cea734f3c8a375a46fdb2d79a") println(standard) println(compact) //sampleEnd }

If you have UUIDs from external sources and must handle invalid input safely, use Uuid.parseOrNull(), Uuid.parseHexDashOrNull(), or Uuid.parseHexOrNull(). These functions return null if the input is invalid:

fun parseId(input: String): Uuid? { return Uuid.parseOrNull(input) }

Convert UUIDs to strings

You can convert a Uuid value to a String value with the following functions:

For example:

import kotlin.uuid.Uuid fun main() { //sampleStart val id = Uuid.parse("de2bc56c-ea73-4f3c-8a37-5a46fdb2d79a") println(id.toString()) // de2bc56c-ea73-4f3c-8a37-5a46fdb2d79a println(id.toHexDashString()) // de2bc56c-ea73-4f3c-8a37-5a46fdb2d79a println(id.toHexString()) // de2bc56cea734f3c8a375a46fdb2d79a //sampleEnd }

Compare UUIDs

You can check whether Uuid values are equal using the == operator.

Kotlin compares values according to the UUID value, not to the textual representation. For example, two values in different forms are equal if they represent the same 128-bit value:

import kotlin.uuid.Uuid fun main() { //sampleStart val first = Uuid.parse("de2bc56c-ea73-4f3c-8a37-5a46fdb2d79a") val second = Uuid.parse("de2bc56cea734f3c8a375a46fdb2d79a") println(first == second) // true //sampleEnd }

This makes the Uuid comparison more reliable than comparing strings, which treats the same value in different formats as different values. Uuid comparison checks the actual identifier value.

Uuid implements the Comparable<Uuid> interface, so UUID values can be sorted with standard collection functions such as sorted(). In that case, Kotlin compares values lexicographically (from the most to the least significant bit):

import kotlin.uuid.Uuid fun main() { //sampleStart val first = Uuid.generateV7() val second = Uuid.generateV7() val sorted = listOf(first, second).sorted() println(sorted) //sampleEnd }

Work with binary representations

Some APIs, storage formats, and binary protocols do not represent UUIDs as strings. Instead, they store the 128-bit UUID value as either:

  • A 16-byte array

  • Two 64-bit values

Use these representations when you need to exchange UUIDs with systems that expect binary UUID data.

To convert between a UUID and a 16-byte representation, use the .toByteArray() and Uuid.fromByteArray() functions:

import kotlin.uuid.Uuid fun main() { //sampleStart val id = Uuid.random() val bytes = id.toByteArray() val original = Uuid.fromByteArray(bytes) println(id) println(bytes) println(original) println(id == original) // true //sampleEnd }

You can also represent the same 128-bit UUID value as two Long values. This is useful because Kotlin doesn't provide a built-in 128-bit integer type. The two Long values store the UUID in two parts:

  • The mostSignificantBits parameter for the first 64 bits of a UUID.

  • The leastSignificantBits parameter for the last 64 bits of a UUID.

To create a Uuid value from two Long values, use the Uuid.fromLongs() function:

import kotlin.uuid.Uuid fun main() { //sampleStart val id = Uuid.fromLongs( mostSignificantBits = -4653685776373167443, leastSignificantBits = -6288180676521310383.toLong() ) println(id) // bf6ac971-52fd-4aad-a8bb-e4fdac78c751 //sampleEnd }

To extract the two parts from an existing Uuid value, use the Uuid.toLongs() function:

import kotlin.uuid.Uuid fun main() { //sampleStart val id = Uuid.random() id.toLongs { mostSignificantBits, leastSignificantBits -> println(mostSignificantBits) println(leastSignificantBits) } //sampleEnd }

Serialize UUIDs

Kotlin supports serialization for Uuid values. Use it to store or transfer a UUID value outside Kotlin code, for example, in JSON APIs or configuration files.

To serialize a Uuid value, represent it as a string unless your application requires another format. The kotlinx.serialization library uses the hex-and-dash format:

//sampleStart import kotlin.uuid.Uuid import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json @Serializable data class User( val id: Uuid, val name: String ) fun main() { val user = User( id = Uuid.parse("de2bc56cea734f3c8a375a46fdb2d79a"), name = "Kotlin" ) println(Json.encodeToString(user)) // {"id":"de2bc56c-ea73-4f3c-8a37-5a46fdb2d79a","name":"Kotlin"} } //sampleEnd

Use UUIDs with Java APIs

Java uses the java.util.UUID class to represent UUIDs. On the JVM, Java APIs may accept or return this type. Although java.util.UUID and kotlin.uuid.Uuid both represent UUIDs, they are two distinct types.

Convert values explicitly to pass UUIDs between Kotlin and Java:

  • Convert a Java UUID to Kotlin with the .toKotlinUuid() extension function:

    import kotlin.uuid.toKotlinUuid val kotlinId: Uuid = javaId.toKotlinUuid()
  • Convert a Kotlin UUID to Java with the .toJavaUuid() extension function:

    import kotlin.uuid.toJavaUuid val javaId: java.util.UUID = kotlinId.toJavaUuid()

These functions allow you to represent your UUID values using Uuid at JVM interoperability boundaries.

Kotlin also provides support for working with Java buffers. Use JVM-specific functions to work with UUIDs in a ByteBuffer:

  • Use the .getUuid() function to read a UUID from a buffer.

  • Use the .putUuid() function to write a UUID to a buffer.

29 May 2026