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, JVM, and Kotlin/JS.
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
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.
Installation
// No installation needed
import java.util.UUID
Available on all JVM targets (Android API 1+, JVM 1.5+). No Gradle dependency required.
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.