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 2.0.20+ adds a multiplatform kotlin.uuid.Uuid API.
  • Both produce standard version 4 UUID strings.

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

Newer Kotlin versions include a standard-library Uuid that works across platforms, not just the JVM.

import kotlin.uuid.Uuid

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

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.

Generate UUID in Kotlin - Java Interop and kotlin.uuid