Kotlin runs on the JVM, Android, and (via Kotlin Multiplatform) native targets. UUID v4 is available without dependencies via java.util.UUID. UUID v7 requires the uuid-creator library until a stdlib addition lands. See UUID in Java and Spring Boot for the JVM background.

UUID v4 — standard library

import java.util.UUID

val id: UUID = UUID.randomUUID()   // UUID v4
val str: String = id.toString()    // "550e8400-e29b-41d4-a716-446655440000"
val back: UUID = UUID.fromString(str)

UUID.randomUUID() uses SecureRandom internally — cryptographically strong, thread-safe. See UUID Security for entropy details.

UUID v7 — uuid-creator library

// build.gradle.kts
dependencies {
    implementation("com.github.f4b6a3:uuid-creator:5.3.3")
}
import com.github.f4b6a3.uuid.UuidCreator

val id: java.util.UUID = UuidCreator.getTimeOrderedEpoch()  // UUID v7
val str = id.toString()   // "018fbe3a-4c5d-7b12-8abc-0123456789ab"

// Extract creation timestamp
val ms: Long = (id.mostSignificantBits ushr 16) and 0x0000_FFFF_FFFF_FFFFL
// Or use the library helper:
val instant = UuidCreator.getInstant(id)

UUID v7’s 48-bit Unix millisecond prefix makes mostSignificantBits ushr 16 a direct timestamp extraction. See UUID Epoch for the arithmetic.

Exposed ORM — PostgreSQL UUID v7

import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import com.github.f4b6a3.uuid.UuidCreator
import java.util.UUID

object Orders : Table("orders") {
    val id         = uuid("id").clientDefault { UuidCreator.getTimeOrderedEpoch() }
    val customerId = uuid("customer_id")
    val status     = varchar("status", 32)
    override val primaryKey = PrimaryKey(id)
}

// Insert
transaction {
    Orders.insert {
        it[customerId] = UUID.fromString("...")
        it[status]     = "pending"
        // id assigned by clientDefault
    }
}

// Time-range query — no secondary createdAt index needed
transaction {
    val since = UuidCreator.getTimeOrderedEpochBoundary(
        System.currentTimeMillis() - 3_600_000L
    )
    Orders.select { Orders.id greaterEq since }
          .orderBy(Orders.id)
          .toList()
}

clientDefault fires before every INSERT when no value is provided. See UUID in Databases for the B-tree index benefits of UUID v7.

Android Room — TypeConverter

// UuidConverter.kt
import androidx.room.TypeConverter
import java.util.UUID

class UuidConverter {
    @TypeConverter
    fun fromString(value: String?): UUID? = value?.let { UUID.fromString(it) }

    @TypeConverter
    fun toString(uuid: UUID?): String? = uuid?.toString()
}

// Database entity
@Entity(tableName = "orders")
data class OrderEntity(
    @PrimaryKey val id: String = UuidCreator.getTimeOrderedEpoch().toString(),
    val customerId: String,
    val status: String,
)

// DAO
@Dao
interface OrderDao {
    @Insert
    suspend fun insert(order: OrderEntity)

    @Query("SELECT * FROM orders WHERE id >= :since ORDER BY id ASC")
    suspend fun ordersSince(since: String): List<OrderEntity>
}

Room with String UUID primary keys sorts UUID v7 correctly because the timestamp prefix is lexicographically ordered. See UUID in Mobile Apps for the full Android pattern.

Kotlin coroutines — thread safety

UUID v7 generation via uuid-creator is thread-safe — the monotonic counter uses atomic operations internally. Generate IDs on the calling coroutine’s thread without a dispatcher switch:

suspend fun createOrder(customerId: UUID): Order {
    val id = UuidCreator.getTimeOrderedEpoch()   // safe on any dispatcher
    return orderRepository.save(Order(id = id, customerId = customerId))
}

See Monotonic Counter for how UUID v7 maintains order within the same millisecond.

Branded types in Kotlin

@JvmInline
value class OrderId(val value: UUID) {
    companion object {
        fun generate(): OrderId = OrderId(UuidCreator.getTimeOrderedEpoch())
        fun from(s: String): OrderId = OrderId(UUID.fromString(s))
    }
}

// Usage — compile-time safety, no runtime overhead
fun getOrder(id: OrderId): Order = repository.findById(id.value)

Kotlin value class wraps UUID with zero boxing overhead on the JVM. See TypeScript UUID Types for the same pattern in TypeScript.

Further reading

External references

Frequently asked questions

How do I generate UUID v7 in Kotlin?

Use the uuid-creator library: UuidCreator.getTimeOrderedEpoch() returns a UUID v7. Alternatively, use the Java java.util.UUID for v4 (UUID.randomUUID()). For Android apps targeting API 26+, uuid-creator is safe — it has no Android-specific dependencies. See UUID in Java for the JVM context.

How does Room store UUIDs in Android?

Room does not have a native UUID column type. Store as String (36-char hyphenated) or ByteArray (16 bytes) with a TypeConverter. For UUID v7 sort order, use ByteArray storage — Room's SQLite TEXT comparison is case-sensitive and sorts correctly for lowercase UUID v7 strings. See UUID in Mobile Apps.