Blog
Wild & Free Tools

Kotlin UUID: Android, Ktor, and Spring Boot Patterns

Last updated: March 2026 5 min read
Quick Answer

Table of Contents

  1. Basic Generation
  2. Android Usage
  3. Ktor Routes
  4. Spring Boot + Kotlin
  5. Extension Functions
  6. Frequently Asked Questions

Kotlin runs on the JVM, so UUID generation is straightforward: java.util.UUID.randomUUID(). The Java UUID class is fully accessible from Kotlin with no boilerplate. This guide covers generation patterns, converting between String and UUID, Android-specific usage, and backend frameworks (Ktor and Spring Boot).

Generating and Converting UUIDs in Kotlin

UUID generation and string conversion:

import java.util.UUID

// Generate a random UUID v4
val id: UUID = UUID.randomUUID()
println(id)  // "550e8400-e29b-41d4-a716-446655440000"

// UUID to String
val idString: String = id.toString()

// String to UUID
val parsed: UUID = UUID.fromString("550e8400-e29b-41d4-a716-446655440000")

// UUID without hyphens
val compact: String = id.toString().replace("-", "")

// Validate a string is a valid UUID (returns null on invalid input)
fun parseUuidOrNull(input: String): UUID? = try {
    UUID.fromString(input)
} catch (e: IllegalArgumentException) {
    null
}

The parseUuidOrNull extension function is idiomatic Kotlin — it uses the null-safety system instead of exceptions for validation.

UUID on Android: Stable Device IDs and Record Keys

On Android, UUID.randomUUID() works on all API levels. Common patterns:

import java.util.UUID
import android.content.SharedPreferences

// Generate a stable installation ID stored in SharedPreferences
fun getOrCreateInstallId(prefs: SharedPreferences): String {
    return prefs.getString("install_id", null) ?: run {
        val newId = UUID.randomUUID().toString()
        prefs.edit().putString("install_id", newId).apply()
        newId
    }
}

// Use UUIDs as local database record IDs (Room)
@Entity(tableName = "workouts")
data class WorkoutEntity(
    @PrimaryKey val id: String = UUID.randomUUID().toString(),
    val name: String,
    val durationMinutes: Int,
    val completedAt: Long = System.currentTimeMillis()
)

Room (Android's ORM) stores the UUID as a TEXT column. This is the standard approach for offline-first apps that sync to a backend — the local record already has a globally unique ID before it reaches the server.

Sell Custom Apparel — We Handle Printing & Free Shipping

Ktor: UUID Path Parameters

Ktor doesn't have built-in UUID path parameter conversion, but it's a one-liner to handle manually:

import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.server.response.*
import io.ktor.http.*
import java.util.UUID

fun Application.configureRouting() {
    routing {
        get("/orders/{id}") {
            val idParam = call.parameters["id"]
                ?: return@get call.respond(HttpStatusCode.BadRequest, "Missing id")

            val orderId = try {
                UUID.fromString(idParam)
            } catch (e: IllegalArgumentException) {
                return@get call.respond(HttpStatusCode.BadRequest, "Invalid UUID format")
            }

            // fetch and return order
            val order = orderService.findById(orderId)
            call.respond(order ?: HttpStatusCode.NotFound)
        }
    }
}

This pattern validates the format and returns a meaningful 400 before hitting your service layer.

Spring Boot with Kotlin: JPA Entity UUID

Spring Boot + Kotlin JPA works identically to Java, with more concise data class syntax:

import jakarta.persistence.*
import java.util.UUID

@Entity
@Table(name = "orders")
data class Order(
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    val id: UUID? = null,

    val customerEmail: String,
    val total: java.math.BigDecimal,
)

// Repository
interface OrderRepository : JpaRepository<Order, UUID>

Using data class with val id: UUID? = null allows Hibernate to populate the ID after the INSERT. The null default is necessary because the ID doesn't exist until the entity is persisted.

Kotlin Extension Functions for UUID Utilities

Idiomatic Kotlin UUID utilities as extension functions:

import java.util.UUID

// Check if a String is a valid UUID
fun String.isValidUuid(): Boolean = try {
    UUID.fromString(this)
    true
} catch (e: IllegalArgumentException) {
    false
}

// Convert String to UUID or throw with a clear message
fun String.toUuid(): UUID = UUID.fromString(this)

// Generate a short ID (first 8 chars of UUID) for display
fun UUID.shortId(): String = toString().substring(0, 8)

// Usage
"not-a-uuid".isValidUuid()  // false
"550e8400-e29b-41d4-a716-446655440000".isValidUuid()  // true
UUID.randomUUID().shortId()  // "550e8400"

Use the free UUID generator above to create test values for Kotlin unit tests, Android instrumentation tests, or Ktor integration tests.

Generate Test UUIDs for Kotlin and Android Tests

The Cheetah UUID Generator produces RFC-compliant UUID v4 strings — paste them into Kotlin unit tests, Room database seeds, or Ktor integration test fixtures.

Open Free UUID Generator

Frequently Asked Questions

Is UUID.randomUUID() thread-safe in Kotlin/JVM?

Yes. java.util.UUID.randomUUID() is thread-safe and can be called concurrently. It uses SecureRandom internally which is also thread-safe.

How do I use UUIDs in Kotlin coroutines?

UUID.randomUUID() is a pure CPU operation with no blocking, so it's safe to call from any coroutine context including Main. No withContext(Dispatchers.IO) needed.

Does Kotlin have a UUID v7 library?

Not in the standard library. UUID v7 (time-ordered) is available through third-party JVM libraries like uuid-creator. The standard java.util.UUID only supports v1, v3, v4, and v5.

How do I serialize UUID to JSON in Kotlin with kotlinx.serialization?

kotlinx.serialization doesn't have a built-in UUID serializer. The standard approach is to store UUIDs as strings and annotate with @Serializable using a custom serializer, or use the uuid string representation directly.

Jennifer Hayes
Jennifer Hayes Business Documents & PDF Writer

Jennifer spent a decade as an executive assistant handling every type of business document imaginable.

More articles by Jennifer →
Launch Your Own Clothing Brand — No Inventory, No Risk