Skip to main content
S

How to Generate UUID in Scala

Using java.util.UUID

Scala runs on the JVM, so UUID generation in Scala means java.util.UUID — the language doesn't ship a separate UUID type of its own. Call UUID.randomUUID() and you get a random, RFC 4122-compliant 128-bit identifier with zero extra dependencies, using the same API Java developers have relied on for years. Below you'll find copy-paste ready code for generating a Scala UUID, safely parsing a string into one with Try, and where to look when you need a sortable v7 format. For cross-platform UUID generation in Flutter, the dart uuid guide covers iOS, Android, and web targets.

Generate UUID in Scala

UUID.randomUUID()
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in Scala

The idiomatic way to generate a UUID in Scala is UUID.randomUUID() via Java interop — Scala has no separate UUID type of its own, so you call the JVM's java.util.UUID class directly. Assign the result to a val and let Scala's type inference handle the rest. The php uuid page covers UUID v3, v4, and v5 generation with the ramsey/uuid package in PHP projects.

Main.scala
import java.util.UUID

val myUuid: UUID = UUID.randomUUID()
println(myUuid)
// Output: 550e8400-e29b-41d4-a716-446655440000

Explanation

Convert a String to a UUID in Scala

Parsing a UUID string in Scala uses the same UUID.fromString() method as Java, which throws an IllegalArgumentException on malformed input rather than returning a safe result. The python uuid generator guide shows how to convert between UUID strings, bytes, and integers for database storage.

Main.scala
import java.util.UUID
import scala.util.Try

val str = "550e8400-e29b-41d4-a716-446655440000"

// Convert the exception-throwing Java API into a safe Option
val maybeUuid: Option[UUID] = Try(UUID.fromString(str)).toOption

maybeUuid match {
  case Some(uuid) => println(s"Valid UUID: $uuid")
  case None       => println("Invalid UUID string")
}

Explanation

Other Options for Generating UUIDs in Scala

java.util.UUID has no native support for UUID version 7, the newer time-sortable format many databases now prefer for primary keys. Since Scala compiles to the JVM, projects that need v7 identifiers reach for the same options available to any Java codebase.

build.sbt
libraryDependencies += "com.github.f4b6a3" % "uuid-creator" % "6.0.0"
Main.scala
import com.github.f4b6a3.uuid.UuidCreator

// Version 7 - Unix timestamp + random, sortable and index-friendly
val uuidV7 = UuidCreator.getTimeOrderedEpoch()
println(uuidV7)

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!