Appearance
Generate UUID in Scala
Since Scala 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 Scala syntax. The following code snippet produces a valid version 4 UUID: Since Scala 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 Scala syntax. The following code snippet produces a valid version 4 UUID:
scala
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:
scala
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
SBT Dependency:
scala
libraryDependencies += "com.github.f4b6a3" % "uuid-creator" % "5.3.2"
Maven Dependency:
xml
<dependency>
<groupId>com.github.f4b6a3</groupId>
<artifactId>uuid-creator</artifactId>
<version>5.3.2</version>
</dependency>
Advanced Scala Usage
UUID Service with Scala Idioms:
scala
import java.util.UUID
import com.github.f4b6a3.uuid.UuidCreator
import scala.util.{Try, Success, Failure}
object UUIDService {
def generateV4(): String = UUID.randomUUID().toString
def generateV7(): String = UuidCreator.getTimeOrderedEpoch().toString
def parseUUID(uuidString: String): Try[UUID] = Try(UUID.fromString(uuidString))
def isValidUUID(uuidString: String): Boolean = parseUUID(uuidString).isSuccess
def getVersion(uuidString: String): Option[Int] =
parseUUID(uuidString).toOption.map(_.version())
}
// Usage with pattern matching
UUIDService.parseUUID("invalid-uuid") match {
case Success(uuid) => println(s"Valid UUID: $uuid")
case Failure(exception) => println(s"Invalid UUID: ${exception.getMessage}")
}
Akka HTTP Integration:
scala
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.StatusCodes
import spray.json.DefaultJsonProtocol._
import spray.json._
import java.util.UUID
import java.time.Instant
case class UUIDResponse(uuid: String, timestamp: String)
implicit val uuidResponseFormat = jsonFormat2(UUIDResponse)
val routes =
path("api" / "uuid") {
get {
val response = UUIDResponse(
UUID.randomUUID().toString,
Instant.now().toString
)
complete(response)
}
}
Play Framework Integration:
scala
import play.api.mvc._
import play.api.libs.json._
import java.util.UUID
import java.time.Instant
class UUIDController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
def generateUUID = Action {
val response = Json.obj(
"uuid" -> UUID.randomUUID().toString,
"timestamp" -> Instant.now().toString
)
Ok(response)
}
def generateNamedUUID(name: String) = Action {
val namespace = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
val namedUUID = UUID.nameUUIDFromBytes((namespace.toString + name).getBytes)
val response = Json.obj(
"uuid" -> namedUUID.toString,
"name" -> name,
"deterministic" -> true
)
Ok(response)
}
}
UUID Version Comparison
Choose the right version for your Scala 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 Scala applications:
- Akka systems: Use Version 4 for actor identification
- Spark jobs: Consider Version 7 for time-ordered data processing
- Play Framework: Use Version 5 for deterministic resource IDs
How do I generate UUID in other languages?
JVM ecosystem:
- Java - Enterprise applications
- Kotlin - Android and server development
- Groovy - Scripting and rapid prototyping
- Clojure - Functional programming
Big data and systems:
- JavaScript - crypto.randomUUID() & uuid library
- Python - Built-in uuid module
- Go - google/uuid package
- Rust - uuid crate