Skip to main content
K

How to Generate UUID in Kotlin

Android & Kotlin Multiplatform

Kotlin doesn't need a separate library to work with unique identifiers — thanks to full JVM interop, java.util.UUID is available in every Kotlin project, Android included. Call UUID.randomUUID() for a random, RFC 4122-compliant UUID in a single line, or parse one back from a string with UUID.fromString() when it arrives from a request body or database row. Below you'll find copy-paste ready code for generating a Kotlin UUID, converting a string safely, and a look at Kotlin's newer multiplatform Uuid API. For SwiftUI @Observable models with UUID primary keys, the swift uuid guide has complete implementation examples.

Generate UUID in Kotlin

UUID.randomUUID()
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in Kotlin

The most straightforward way to generate a UUID in Kotlin is UUID.randomUUID() from java.util.UUID — since Kotlin compiles to JVM bytecode, this API is available with zero extra setup and works identically on Android. The rust uuid reference shows how to use uuid::Uuid::new_v4() with zero-cost abstractions.

main.kt
import java.util.UUID

fun main() {
    val myUuid: UUID = UUID.randomUUID()
    println(myUuid)
    // Output: 550e8400-e29b-41d4-a716-446655440000
}

Explanation

Convert a String to a UUID in Kotlin

When a UUID arrives as a string — from a network response, a config file, or a database column — parse it back into a type-safe UUID with UUID.fromString(). The call throws IllegalArgumentException on malformed input, so wrap it safely using Kotlin's null-safety idioms. The bash uuid guide covers uuidgen, /proc/sys/kernel/random/uuid, and Python one-liners for shell scripting.

main.kt
import java.util.UUID

fun String.toUuidOrNull(): UUID? =
    runCatching { UUID.fromString(this) }.getOrNull()

fun main() {
    val valid = "550e8400-e29b-41d4-a716-446655440000".toUuidOrNull()
    val invalid = "not-a-uuid".toUuidOrNull()

    println(valid)    // 550e8400-e29b-41d4-a716-446655440000
    println(invalid)  // null
}

Explanation

Other Options for Generating UUIDs in Kotlin

UUID.randomUUID() covers most use cases, but Kotlin's standard library also has its own native multiplatform Uuid API, added in Kotlin 2.0.20 as an alternative to java.util.UUID for projects that don't target the JVM.

main.kt
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid

@OptIn(ExperimentalUuidApi::class)
fun main() {
    // Works on JVM, Native, JS, and Wasm targets alike
    val myUuid = Uuid.random()
    println(myUuid)
}

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!