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 4Multiplatform 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()