Code guide

Generate UUIDs in Kotlin

Generate UUIDs in Kotlin via Java interop or the multiplatform kotlin.uuid API, with parsing examples.

Kotlin can use the JVM UUID class directly, and recent Kotlin releases add a multiplatform Uuid type in the standard library.

Key takeaways

  • On the JVM, java.util.UUID.randomUUID() works directly.
  • kotlin.uuid supports multiplatform code; older compiler releases require experimental opt-in.
  • Both produce standard version 4 UUID strings.

For implementation context, continue with Java, UUID v4, and UUID Versions. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.

JVM interop (works everywhere on the JVM)

The simplest option on the JVM is the familiar Java UUID class, called straight from Kotlin.

val id = java.util.UUID.randomUUID().toString()  // version 4

Multiplatform kotlin.uuid

The kotlin.uuid API works across platforms. It was introduced experimentally in Kotlin 2.0.20, so check the documentation for your compiler version. Releases where it is experimental require an ExperimentalUuidApi opt-in; current stable API documentation may show different version requirements.

// For compiler releases where kotlin.uuid is experimental:
@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)

import kotlin.uuid.Uuid

val id = Uuid.random()                 // version 4
val parsed = Uuid.parse("018f2f7a-07b2-7d6e-9c37-43e1577b8b44")

Handle invalid JVM input without crashing a handler

For a JVM endpoint, wrap UUID.fromString in runCatching and decide how to report invalid input. Compare against the canonical representation if the endpoint requires complete hyphenated text. This approach uses java.util.UUID and does not require the multiplatform API.

Return the typed value to application code, and convert it to a string only at serialization boundaries. Keep authorization checks separate from parsing.

fun parseCanonicalUuid(input: String): java.util.UUID? =
    runCatching {
        java.util.UUID.fromString(input).also { id ->
            require(id.toString().equals(input, ignoreCase = true))
        }
    }.getOrNull()

FAQ

Generate UUIDs in Kotlin questions

How do I generate a UUID in Kotlin?

On the JVM call java.util.UUID.randomUUID(). On recent Kotlin releases you can use kotlin.uuid.Uuid.random() for multiplatform code.

Is kotlin.uuid available on all platforms?

The kotlin.uuid.Uuid API is multiplatform in recent Kotlin versions, unlike java.util.UUID which is JVM only.

Which should I use?

Use java.util.UUID for JVM-only projects, and kotlin.uuid for shared multiplatform code.

Primary references

Standards and technical sources

The implementation and guidance on this page are checked against these standards and platform documentation sources.

Generate UUID in Kotlin - Java Interop and kotlin.uuid