random

Generates a new random Uuid instance.

The returned uuid conforms to the IETF variant (variant 2) and version 4, designed to be unique with a very high probability, regardless of when or where it is generated. 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 4 uuid has a partially predictable bit pattern, and utilizes at most 122 bits of entropy, regardless of platform.

The following APIs are used for producing the random uuid in each of the supported targets:

Note that the underlying API used to produce random uuids may change in the future.

Since Kotlin

2.0

Return

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.uuid.*

fun main() { 
   //sampleStart 
   // Generates a random and unique uuid each time
val uuid1 = Uuid.random()
val uuid2 = Uuid.random()
val uuid3 = Uuid.random()

println(uuid1 == uuid2) // false
println(uuid1 == uuid3) // false
println(uuid2 == uuid3) // false 
   //sampleEnd
}