Developer Lab · Kotlin
Generate UUID in Kotlin
Kotlin uses java.util.UUID from the JVM standard library - zero dependencies. UUID.randomUUID() gives you a SecureRandom-backed v4 UUID. Works on Android and the JVM. For Kotlin/JS or Native, use the multiplatform kotlin.uuid.Uuid API.
Quick Reference
| Method | Version | Sortable | Use Case |
|---|---|---|---|
| UUID.randomUUID() | v4 | No | General purpose - zero deps, JVM built-in |
| UUID.fromString() | any | - | Parse - throws IllegalArgumentException on invalid |
| fun uuid() extension | v4 | No | Kotlin idiom - extension function wrapper |
Primary Implementation
import java.util.UUID
// UUID v4 - random, SecureRandom-backed, zero dependencies
val id: UUID = UUID.randomUUID()
println(id)
// → f47ac10b-58cc-4372-a567-0e02b2c3d479
// As a string
val idStr: String = id.toString()
// Kotlin extension function for cleaner API
fun uuid(): String = UUID.randomUUID().toString()
val newId = uuid()
// Parse and validate
try {
val parsed = UUID.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479")
println("Version: ${parsed.version()}") // → 4
} catch (e: IllegalArgumentException) {
println("Invalid UUID: ${e.message}")
}
// Safe parse with runCatching
val result = runCatching { UUID.fromString("invalid") }
result.onFailure { println("Parse failed: ${it.message}") }
// Generate multiple
val ids = List(5) { UUID.randomUUID() }All UUID Versions
UUID v4 - Random (JVM built-in)
import java.util.UUID
val id = UUID.randomUUID()
println(id.toString()) // → "550e8400-e29b-41d4-a716-446655440000"Kotlin extension - idiomatic wrapper
import java.util.UUID
// Idiomatic Kotlin - extension on companion object
fun UUID.Companion.random(): UUID = UUID.randomUUID()
fun UUID.Companion.randomString(): String = UUID.randomUUID().toString()
// Usage
val id = UUID.random()
val idStr = UUID.randomString()Spring Boot JPA - UUID primary key
import jakarta.persistence.*
import java.util.UUID
@Entity
@Table(name = "orders")
data class Order(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
val id: UUID = UUID.randomUUID(),
val customerName: String,
val totalAmount: Long,
)Real-World Use Cases
1. Android Room database - UUID primary key
import androidx.room.*
import java.util.UUID
@Entity(tableName = "notes")
data class Note(
@PrimaryKey
val id: String = UUID.randomUUID().toString(), // Room stores as TEXT
val title: String,
val content: String,
)
@Dao
interface NoteDao {
@Insert suspend fun insert(note: Note)
@Query("SELECT * FROM notes WHERE id = :id")
suspend fun findById(id: String): Note?
}2. Ktor server - request tracing
import io.ktor.server.application.*
import io.ktor.server.plugins.callid.*
import java.util.UUID
fun Application.configureMonitoring() {
install(CallId) {
// Generate a UUID for every request
generate { UUID.randomUUID().toString() }
replyToHeader(HttpHeaders.XRequestId)
}
}3. Kotlin coroutine job ID
import kotlinx.coroutines.*
import java.util.UUID
suspend fun processOrder(orderId: String) {
val jobId = UUID.randomUUID().toString()
withContext(Dispatchers.IO) {
println("[$jobId] Processing order $orderId")
// ... processing logic
println("[$jobId] Order $orderId complete")
}
}Common Mistakes
Not handling IllegalArgumentException on parse
UUID.fromString() throws IllegalArgumentException for invalid input. Always wrap in try-catch or use runCatching { UUID.fromString(str) } for safe parsing.
Calling .toString() in hot paths
Each .toString() call allocates a new String on the heap. Store UUID objects in data classes and only convert to string at the DB write or API response boundary.
Using String instead of UUID type in data classes
Storing IDs as String in data classes loses type safety - you can accidentally pass a userId where an orderId is expected. Use the UUID type in your domain model.
How It Works
Kotlin's UUID.randomUUID() delegates to Java's java.util.UUID, which uses SecureRandom internally. SecureRandom is seeded from the OS entropy pool and is thread-safe.
The UUID object stores two Long values (most/least significant bits). It is immutable and implements Comparable<UUID> and Serializable.
Output Formats
id.toString()
f47ac10b-58cc-4372-a567-0e02b2c3d479
No hyphens
id.toString().replace("-", "")
mostSignificantBits
id.mostSignificantBits (Long)
Best Practices, Performance, and Security
Best practices
Use UUID type in data classes - only call .toString() at API/DB boundaries.
Use runCatching { UUID.fromString(str) } for safe parsing without exceptions.
In Spring Boot 3+, use @GeneratedValue(strategy = GenerationType.UUID) for JPA entities.
Performance
Kotlin/JVM generates roughly 2–5 million UUIDs/second - same as Java. SecureRandom is thread-safe and uses a shared instance.
The UUID object is ~32 bytes on the heap. For bulk generation, batch DB inserts rather than generating UUIDs in a tight loop.
Security
Entropy source: SecureRandom - seeded from the OS entropy pool. Cryptographically secure on all platforms.
Suitable for session tokens, CSRF tokens, and API keys. SecureRandom is thread-safe - no synchronization needed.
Installation
UUID v4 (java.util.UUID)
// No installation needed
import java.util.UUIDAvailable on all JVM targets (Android API 1+, JVM 1.5+). No Gradle dependency required.
Frequently Asked Questions
How do I generate a UUID in Kotlin?
Kotlin uses java.util.UUID from the JVM standard library: java.util.UUID.randomUUID().toString() returns a random v4 UUID backed by SecureRandom. Kotlin 2.0+ also adds the multiplatform kotlin.uuid.Uuid (kotlin.uuid.Uuid.random()) for JVM, JS, and Native targets. For v7, use a JVM library such as java-uuid-generator.
Is UUID.randomUUID() cryptographically secure?
Yes. UUID.randomUUID() uses the platform CSPRNG (operating system secure random source), suitable for session tokens, API keys, and idempotency keys. Do not use non-cryptographic random sources for security-sensitive identifiers.
What is the difference between UUID v4 and v7 in Kotlin?
UUID v4 (UUID.randomUUID() or equivalent) is fully random and not sortable. UUID v7 embeds a millisecond timestamp for chronological sorting (RFC 9562). Use v4 for general-purpose IDs; use v7 for database primary keys at scale.
Do I need to install a package for UUID generation in Kotlin?
No additional package is required for basic v4 generation in Kotlin. Check the Installation section for version-specific notes.
How do I validate a UUID string in Kotlin?
Use the platform's UUID parse/validation function, or test against the RFC 4122 regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i. Always validate external input at API boundaries.
Should I use UUIDs as database primary keys in Kotlin applications?
UUIDs work well as primary keys for distributed systems. Prefer native UUID/BINARY(16) column types over VARCHAR(36). For very large tables, consider UUID v7 for better B-tree insert locality.
Can I generate UUIDs in Kotlin without a network connection?
Yes. UUID generation uses local OS entropy sources and does not require network access. Each call is independent and thread-safe on modern platforms.
What output formats are available in Kotlin?
The standard hyphenated lowercase string (36 chars) is the default. Most APIs also support 32-char hex (no hyphens) and 16-byte binary formats. Use string format for APIs and binary for database storage.
What RFC standards apply to Kotlin UUID generation?
Version 4 UUIDs follow RFC 4122. UUID v7 follows RFC 9562 (May 2024). Ensure your chosen method produces compliant version and variant bits.
When should I avoid UUID v1?
Avoid UUID v1 in security-sensitive contexts - it embeds MAC address and timestamp information. Prefer v4 (UUID.randomUUID() or equivalent) unless you need legacy Cassandra timeuuid compatibility.
Key definitions
- UUID
- 128-bit universally unique identifier, usually shown as 36 hex characters with hyphens.
- CSPRNG
- Cryptographically secure pseudo-random number generator - the entropy source behind secure UUID generation.
- RFC 4122
- IETF standard defining UUID versions 1 through 5. Version 4 is random.
- RFC 9562
- IETF standard adding UUID versions 6, 7, and 8. Version 7 is time-ordered.