Generate UUID with Scala and Java Interop
Scala seamlessly uses Java's UUID class from java.util package, providing full interoperability with the Java ecosystem. Import UUID and use randomUUID() for cryptographically secure random UUID generation in your Scala applications.
Built-in Java Interop
No additional dependencies needed - use java.util.UUID directly from Scala!
import java.util.UUID
// Generate random UUID v4
val uuid = UUID.randomUUID()
println(uuid) // 550e8400-e29b-41d4-a716-446655440000
Functional UUID Generation Patterns
Apply Scala's functional programming capabilities to UUID generation using map, flatMap, and for-comprehensions. Create UUID-generating functions that integrate cleanly with Scala's functional abstractions and collection operations.
import java.util.UUID
// Generate single UUID
val uuid = UUID.randomUUID()
println(uuid)
// Get as string
val uuidString = uuid.toString
// Generate multiple UUIDs functionally
val uuids = (1 to 5).map(_ => UUID.randomUUID())
uuids.foreach(println)
// Generate with List comprehension
val uuidList = List.fill(5)(UUID.randomUUID())
// Map over collection with UUIDs
case class User(id: UUID, name: String)
val users = List("Alice", "Bob", "Charlie").map(name =>
User(UUID.randomUUID(), name)
)
Safe UUID Parsing with Option and Try
Leverage Scala's Option and Try types for safe UUID parsing without exceptions. These functional error-handling patterns provide compile-time safety and make invalid UUID handling explicit in your type signatures.
Option-based Parsing
import java.util.UUID
import scala.util.Try
// Safe parsing with Option
def parseUUID(str: String): Option[UUID] =
Try(UUID.fromString(str)).toOption
// Usage
parseUUID("550e8400-e29b-41d4-a716-446655440000") match {
case Some(uuid) => println(s"Valid: $uuid")
case None => println("Invalid UUID")
}
Try-based Error Handling
import scala.util.{Try, Success, Failure}
// Try-based parsing
def tryParseUUID(str: String): Try[UUID] =
Try(UUID.fromString(str))
tryParseUUID("invalid") match {
case Success(uuid) => println(uuid)
case Failure(ex) => println(s"Error: ${ex.getMessage}")
}
Case Classes with UUID Primary Keys
Scala's case classes provide immutable data structures perfect for domain modeling with UUID identifiers. Use default parameters to auto-generate UUIDs on object creation, ensuring every instance has a unique identifier.
import java.util.UUID
// Case class with auto-generated UUID
case class User(
id: UUID = UUID.randomUUID(),
name: String,
email: String
)
// Create users with auto-generated IDs
val user1 = User(name = "Alice", email = "alice@example.com")
val user2 = User(name = "Bob", email = "bob@example.com")
println(user1.id) // Auto-generated UUID
println(user2.id) // Different UUID
// Explicit UUID
val userWithId = User(
id = UUID.fromString("550e8400-e29b-41d4-a716-446655440000"),
name = "Charlie",
email = "charlie@example.com"
)
// Companion object factory
object User {
def create(name: String, email: String): User = {
User(UUID.randomUUID(), name, email)
}
}
Validation with Custom Types
Create type-safe UUID wrappers using Scala's type system to prevent mixing different kinds of identifiers. Value classes provide zero-runtime overhead while maintaining compile-time type safety.
import java.util.UUID
import scala.util.Try
// Validation helper
def isValidUUID(str: String): Boolean =
Try(UUID.fromString(str)).isSuccess
// Filter valid UUIDs from list
val inputs = List(
"550e8400-e29b-41d4-a716-446655440000",
"invalid-uuid",
"6ba7b810-9dad-11d1-80b4-00c04fd430c8"
)
val validUUIDs = inputs.flatMap(parseUUID)
// Validation in for-comprehension
def processUUID(uuidStr: String): Option[String] = for {
uuid <- parseUUID(uuidStr)
result = s"Processing: $uuid"
} yield result
Slick Database Integration
Integrate UUIDs with Slick, Scala's functional relational mapping library. Define custom column types for UUID fields and leverage Slick's type-safe query DSL for database operations with UUID primary keys.
import slick.jdbc.PostgresProfile.api._
import java.util.UUID
case class User(id: UUID, name: String, email: String)
class Users(tag: Tag) extends Table[User](tag, "users") {
def id = column[UUID]("id", O.PrimaryKey)
def name = column[String]("name")
def email = column[String]("email")
def * = (id, name, email) <> (User.tupled, User.unapply)
}
val users = TableQuery[Users]
// Insert user with UUID
val insertUser = users += User(
UUID.randomUUID(),
"Alice",
"alice@example.com"
)
// Query by UUID
def findUser(id: UUID) = users.filter(_.id === id).result.headOption