generateV7
Generates a new random Uuid Version 7 instance.
The returned uuid is a time-based sortable UUID that conforms to the IETF variant (variant 2) and version 7, uses UNIX timestamp in milliseconds as a prefix and a randomly generated suffix, allowing several consecutively generated uuids to be monotonically ordered and yet keep future uuid values unguessable.
The current implementation guarantees strict monotonicity of returned uuids within the scope of an application lifetime. There are no monotonicity guarantees for two uuids generated in separate processes on the same host, as well as for uudis generated on different hosts. If multiple uuids were requested at the exact same instant of time, the current implementation will use the "Fixed Bit-Length Dedicated Counter" method covered by the RFC-9562, §6.2. Monotonicity and Counters to achieve strict monotonicity.
The random part of the uuid is produced using a cryptographically secure pseudorandom number generator (CSPRNG) available on the platform. If the underlying system has not collected enough entropy, this function may block until sufficient entropy is collected, and the CSPRNG is fully initialized. It is worth mentioning that the PRNG used in the Kotlin/WasmWasi target is not guaranteed to be cryptographically secure. See the list below for details about the API used for producing the random uuid in each supported target.
Note that the returned uuid is not recommended for use for cryptographic purposes. Because version 7 uuid has a partially predictable bit pattern, and utilizes at most 74 bits of entropy, regardless of platform.
The following APIs are used for producing the random uuid in each of the supported targets:
Kotlin/JVM - java.security.SecureRandom
Kotlin/JS - Crypto.getRandomValues()
Kotlin/WasmJs - Crypto.getRandomValues()
Kotlin/WasmWasi - random_get
Kotlin/Native:
Linux targets - getrandom
Apple and Android Native targets - arc4random_buf
Windows targets - BCryptGenRandom
Note that the underlying API used to produce random uuids may change in the future.
Since Kotlin
2.3Return
A randomly generated uuid.
Throws
if the underlying API fails. Refer to the corresponding underlying API documentation for possible reasons for failure and guidance on how to handle them.
Samples
import kotlin.test.*
import kotlin.time.Instant
import kotlin.uuid.*
fun main() {
//sampleStart
// Generates a random, unique and strictly ordered uuids each time
val uuid1 = Uuid.generateV7()
val uuid2 = Uuid.generateV7()
val uuid3 = Uuid.generateV7()
println(uuid1 < uuid2) // true
println(uuid1 < uuid3) // true
println(uuid2 < uuid3) // true
//sampleEnd
}