Skip to content

Generate UUID in Kotlin

Since Kotlin is a JVM-based language, we can use the same libraries and methods we would have used in Java to generate UUIDs, as long as we do so in Kotlin syntax. The following code snippet produces a valid version 4 UUID:

kotlin
import java.util.UUID
println(UUID.randomUUID())

If you need to generate a specific UUID version, you need to use a third-party library such as uuid-creator which offers more flexible options:

kotlin
import com.github.f4b6a3.uuid.UuidCreator

//generate UUID version 1
val uuid = UuidCreator.getTimeBased()

//generate UUID version 2
val uuid = UuidCreator.getDceSecurity(UuidLocalDomain.LOCAL_DOMAIN_PERSON, 1234)

//generate UUID version 3
val uuid = UuidCreator.getNameBasedMd5(UuidNamespace.NAMESPACE_URL, "https://github.com/")

//generate UUID version 4
val uuid = UuidCreator.getRandomBased()

//generate UUID version 5
val uuid = UuidCreator.getNameBasedSha1(UuidNamespace.NAMESPACE_URL, "https://github.com/")

//generate UUID version 6
val uuid = UuidCreator.getTimeOrdered()

//generate UUID version 7
val uuid = UuidCreator.getTimeOrderedEpoch()

Installation & Setup

Gradle Kotlin DSL:

kotlin
dependencies {
    implementation("com.github.f4b6a3:uuid-creator:5.3.2")
}

Gradle Groovy:

groovy
implementation 'com.github.f4b6a3:uuid-creator:5.3.2'

Advanced Kotlin Usage

UUID Service with Kotlin Features:

kotlin
import java.util.UUID
import com.github.f4b6a3.uuid.UuidCreator

object UUIDService {
    
    fun generateV4(): String = UUID.randomUUID().toString()
    
    fun generateV7(): String = UuidCreator.getTimeOrderedEpoch().toString()
    
    fun String.isValidUUID(): Boolean = try {
        UUID.fromString(this)
        true
    } catch (e: IllegalArgumentException) {
        false
    }
    
    fun String.toUUIDOrNull(): UUID? = try {
        UUID.fromString(this)
    } catch (e: IllegalArgumentException) {
        null
    }
    
    fun String.getUUIDVersion(): Int? = toUUIDOrNull()?.version()
}

// Usage with extension functions
fun main() {
    val uuidString = UUIDService.generateV4()
    println("Valid: ${uuidString.isValidUUID()}")
    println("Version: ${uuidString.getUUIDVersion()}")
}

Spring Boot with Kotlin:

kotlin
import org.springframework.web.bind.annotation.*
import java.util.UUID
import java.time.Instant

data class UUIDResponse(
    val uuid: String,
    val timestamp: String
)

@RestController
@RequestMapping("/api")
class UUIDController {
    
    @GetMapping("/uuid")
    fun generateUUID(): UUIDResponse = UUIDResponse(
        uuid = UUID.randomUUID().toString(),
        timestamp = Instant.now().toString()
    )
    
    @GetMapping("/uuid/{name}")
    fun generateNamedUUID(@PathVariable name: String): Map<String, Any> {
        val namespace = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
        val namedUUID = UUID.nameUUIDFromBytes("$namespace$name".toByteArray())
        
        return mapOf(
            "uuid" to namedUUID.toString(),
            "name" to name,
            "deterministic" to true
        )
    }
}

Android Integration:

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

class DeviceIdManager(context: Context) {
    
    private val prefs: SharedPreferences = context.getSharedPreferences(
        "device_prefs", Context.MODE_PRIVATE
    )
    
    fun getDeviceId(): String {
        return prefs.getString("device_id", null) ?: generateAndSaveDeviceId()
    }
    
    private fun generateAndSaveDeviceId(): String {
        val deviceId = UUID.randomUUID().toString()
        prefs.edit().putString("device_id", deviceId).apply()
        return deviceId
    }
    
    fun generateSessionId(): String = UUID.randomUUID().toString()
}

UUID Version Comparison

Choose the right version for your Kotlin application:

  • Version 1 - Time-based, includes MAC address
  • Version 3 - MD5 namespace-based, deterministic
  • Version 4 - Random, most popular choice
  • Version 5 - SHA-1 namespace-based, more secure than v3
  • Version 6 - Time-ordered, better than v1 for databases
  • Version 7 - Modern time-based with improved sorting

For Kotlin applications:

  • Android apps: Use Version 4 for local database entities
  • Spring Boot APIs: Consider Version 7 for microservice communication
  • Multiplatform projects: Use Version 5 for cross-platform consistency

How do I generate UUID in other languages?

JVM ecosystem:

  • Java - Enterprise applications and Android
  • Scala - Big data and functional programming
  • Groovy - Scripting and rapid development

Mobile development:

  • Swift - iOS native development
  • Dart - Flutter cross-platform

Web and systems:

  • JavaScript - crypto.randomUUID() & uuid library
  • Python - Built-in uuid module
  • Go - google/uuid package

← Back to Online UUID Generator