[//]: # (This file was autogenerated using zio-sbt-website plugin via sbt generateReadme command.) [//]: # (So please do not edit it manually. Instead, change "docs/index.md" file or sbt setting keys) [//]: # (e.g. "readmeDocumentation" and "readmeSupport".) Modular building blocks for modern Scala applications—no effect system required. What Is ZIO Blocks? ZIO Blocks is a family of type-safe, modular building…
Modular building blocks for modern Scala applications—no effect system required.
What Is ZIO Blocks?
ZIO Blocks is a family of type-safe, modular building blocks for Scala applications. Each block is a standalone library with zero or minimal dependencies, designed to work with any Scala stack—ZIO, Cats Effect, Kyo, Ox, Akka, or plain Scala.
The philosophy is simple: use what you need, nothing more. Each block is independently useful and designed to compose with other blocks or your existing code.
Core Principles
Zero Lock-In: No dependency on ZIO, Cats Effect, or any other effect system. Use a block with whatever stack you already have.
Modular: Each block is a separate artifact. Depend on exactly what you need.
Cross-Platform: Most blocks build for JVM and Scala.js on Scala 3.9 (LTS) and 3.10 (Scala Next). Five foundation modules — chunk, typeid, maybe, markdown and schema — also build for Scala 2.13, on the JVM only. The catalog below records the versions per block.
High Performance: Implementations that avoid boxing, minimize allocations, and use platform-specific features where they pay off.
Type Safety: Scala’s type system carries the correctness guarantees, without runtime overhead.
That line is for Scala 2.13 and Scala 3.9. On Scala 3.10 and newer, use zio-blocks-next-schema and add scalacOptions += "-experimental". See How to Add ZIO Blocks to Your Build for Scala.js, scala-cli, and cross-building.
import zio.blocks.schema._
case class Person(name: String, age: Int)
object Person {
implicit val schema: Schema[Person] = Schema.derived
}
val alice = Person("Alice", 30)
// One schema, every format
val jsonStr = alice.toJsonString // {"name":"Alice","age":30}
val parsed = """{"name":"Bob","age":25}""".fromJson[Person]
New to ZIO Blocks? Getting Started is a short tour of the core ideas, and the Your First Schema tutorial is the first hands-on lesson.
The four blocks below get a full walkthrough because they have no close
equivalent elsewhere in Scala. Every other block is one row away in the catalog,
and each row links to its own reference page.
All Blocks
Every block is published under the dev.zio organization. Most build for Scala 3.9 and 3.10
on JVM and Scala.js. The five foundation modules — chunk, typeid, maybe, markdown and
schema — additionally build for Scala 2.13, on the JVM only; every other module is Scala 3
only. Each row records its own versions.
Meta Programming
JSON support is built into zio-blocks-schema; the modules below add further formats.
Smithy IDL parser and AST library for API modeling
Schema
The Schema block brings dynamic-language productivity to statically-typed Scala. Define your data types once, and derive codecs, validators, optics, and more automatically.
The Problem
In statically-typed languages, you often maintain separate codec implementations for each data format (JSON, Avro, Protobuf, etc.). Meanwhile, dynamic languages handle data effortlessly:
// JavaScript: one line and doneconst data =await res.json();
In Scala, you’d typically need separate codecs for each format—a significant productivity gap.
The Solution
ZIO Blocks Schema derives everything from a single schema definition:
case class Person(name: String, age: Int)
object Person {
implicit val schema: Schema[Person] = Schema.derived
}
// Derive codecs for any format:
val jsonCodec = Schema[Person].derive(JsonFormat) // JSON
val avroCodec = Schema[Person].derive(AvroFormat) // Avro
val toonCodec = Schema[Person].derive(ToonFormat) // TOON (LLM-optimized)
val msgpackCodec = Schema[Person].derive(MessagePackFormat) // MessagePack
val thriftCodec = Schema[Person].derive(ThriftFormat) // Thrift
Key Features
Universal Data Formats: JSON built in, plus Avro, BSON, CSV, MessagePack, Thrift, TOON, XML, and YAML as separate modules, with Protobuf planned.
High Performance: Register-based design stores primitives directly in byte arrays, enabling zero-allocation serialization.
Reflective Optics: Type-safe lenses, prisms, and traversals with embedded structural metadata.
Automatic Derivation: Derive type class instances for any type with a schema.
See the Meta Programming rows above for the optional format modules.
Example
import zio.blocks.schema._
case class Address(street: String, city: String)
case class Person(name: String, age: Int, address: Address)
object Person extends CompanionOptics[Person] {
implicit val schema: Schema[Person] = Schema.derived
val name: Lens[Person, String] = $(_.name)
val age: Lens[Person, Int] = $(_.age)
val streetName: Lens[Person, String] = $(_.address.street)
}
val person = Person("Alice", 30, Address("123 Main St", "Springfield"))
val updated = Person.age.replace(person, 31)
Learn More
Your First Schema — a getting-started tutorial: describe a type once, round-trip it through JSON, and read decode errors
Evolve Your Data — a tutorial that validates incoming data with Into, converts between versions with As, and renames a stored field with a compile-checked Migration
One Type, Many Formats — a tutorial that exports one catalog as JSON, YAML, XML, TOON, MessagePack, Avro and CSV from the same schema
How to Encode and Decode Records with Avro — a how-to guide that writes the .avsc schema for a sealed trait, streams Avro records, maps each Scala type to its Avro type, and reads the bytes with Apache Avro
How to Store Case Classes in MongoDB — a how-to guide that derives a BSON codec, uses ObjectId as the _id, chooses how sealed traits and options are stored, and inserts and queries tickets with the MongoDB Java driver
Schema reference — the full API surface, from Reflect and Binding through optics, validation, and schema evolution
Compile-time verified resource safety for synchronous Scala code. Scope prevents resource leaks at compile time by tagging values with an unnameable type-level identity—values allocated in a scope can only be used within that scope. Child scope values cannot escape to parent scopes, enforced by both the abstract scope-tagged type and the Unscoped constraint on scoped.
The Problem
Resource management in Scala is error-prone:
// Classic try/finally - verbose and easy to get wrong
val db = openDatabase()
try {
val tx = db.beginTransaction()
try {
doWork(tx)
tx.commit()
} finally tx.close() // What if commit() throws?
} finally db.close()
// Using - better, but doesn't prevent returning resources
Using(openDatabase()) { db =>
db // Oops! Returned the resource - use after close!
}
The Solution
Scope makes resource leaks a compile error, not a runtime bug:
import zio.blocks.scope.*
Scope.global.scoped { scope =>
import scope.*
val db: $[Database] = allocate(Resource(openDatabase()))
// Methods are hidden - can't call db.query() directly
// Must use $ to access:
val result: String = $(db)(_.query("SELECT 1"))
// Trying to return `db` would be a compile error!
result // Only pure data (String) escapes
}
// db.close() called automatically
Key Features
Compile-Time Leak Prevention: Values of type scope.$[A] are opaque and unique to each scope instance. Returning a scoped value from its scope is a type error.
Zero Runtime Overhead: $[A] erases to A at runtime—zero allocation overhead.
Structured Scopes: Child scopes nest within parents; resources clean up LIFO when scopes exit.
Built-in Dependency Injection: Wire up your application with Resource.from[T](wires*) for automatic constructor-based DI.
AutoCloseable Integration: Resources implementing AutoCloseable have close() registered automatically.
Unscoped Constraint: The scoped method requires Unscoped[A] evidence on the return type, ensuring only pure data (not resources or closures) can escape.
Actionable Runtime Errors: If a scope reference escapes and is used after closing, allocate, open(), and $ throw IllegalStateException with a detailed message explaining what went wrong, the common causes, and how to fix it—no silent null returns.
A lightweight, zero-dependency asynchronous effect type. A ready Async[A]is
an A, so synchronous code composed with map / flatMap allocates nothing on
the happy path while still suspending on genuinely asynchronous work.
The Problem
Asynchronous Scala forces a choice between two costs. Future allocates for
every combinator and needs an ExecutionContext threaded everywhere, even when
the value is already available. Full effect systems avoid that but ask you to
adopt a runtime, a set of type classes, and a programming model across your
whole codebase—a heavy price for a library that only occasionally suspends.
The Solution
Async[A] is a value, not a wrapper. When the result is already known, the
representation is the result, so composing ready values costs nothing:
import zio.blocks.async._
// Constructors collapse to bare values; transformers inline with no allocation
val computed: Int =
Async.succeed(20).map(_ + 1).flatMap(n => Async.succeed(n * 2)).block
// computed: Int = 42
Key Features
Zero Allocation on the Happy Path: A completed Async[A] is represented as the A itself; map and flatMap over ready values allocate nothing.
Direct-Style await: Async.async { ... } rewrites .await calls at compile time into a non-blocking flatMap chain—straight-line code, asynchronous execution.
No Runtime to Adopt: No ExecutionContext to thread, no type class hierarchy, no effect system dependency.
Interop Built In: Bridges to Future and CompletionStage, plus Async.promise for callback-based APIs.
Write straight-line asynchronous code with Async.async and .await, rewritten
at compile time into a non-blocking flatMap chain:
import zio.blocks.async._
def fetch(id: Int): Async[String] = Async.succeed(s"item-$id")
val program: Async[Int] =
Async.async {
val a = fetch(1).await
val b = fetch(2).await
(a + b).length
}
A thin, type-safe JDBC wrapper that maps Scala case classes to database tables using the same Schema you use for JSON and Avro codecs. No ORM runtime, no code generation — just composable SQL fragments, a derived repository abstraction, and a direct ZIO integration.
The Problem
JDBC is powerful but tedious: manual ResultSet traversal, index-based parameter binding, and repetitive CRUD boilerplate make even simple database access error-prone. ORMs solve the boilerplate but add heavy runtimes, hidden queries, and opaque magic.
The Solution
ZIO Blocks SQL derives everything from a single Schema[A]:
case class User(id: Long, name: String, email: String)
object User:
given Schema[User] = Schema.derived
// Derive the table, codec, and repository in one line
val repo = Repo.derived[User, Long]
// Use the sql"..." interpolator for custom queries
val frag = sql"SELECT * FROM user WHERE email = ${"[email protected]"}"
Key Features
Schema-derived codecs: DbCodec[A] is auto-derived from Schema[A] — column names, types, and nullability come for free.
Composable fragments: The sql"..." interpolator creates Frag values that compose safely with ++. SQL injection is structurally impossible.
CRUD repository: Repo[E, ID] provides all, find, findAll, insert, insertAll, update, delete, deleteAll, and clear out of the box.
DDL generation: Table.createTable(dialect) generates type-accurate CREATE TABLE IF NOT EXISTS SQL from the schema.
ZIO integration: TransactorZIO lifts blocking JDBC calls into Task (or ZIO) with proper bracketing and rollback.
Effect-system agnostic core: The zio-blocks-sql module has no ZIO dependency — use it with any effect system or plain Scala.
import zio.blocks.schema._
import zio.blocks.sql._
case class Product(id: Long, name: String, price: Double)
object Product:
given Schema[Product] = Schema.derived
given DbCodec[Product] = summon[Schema[Product]].deriving(DbCodecDeriver).derive
val repo = Repo.derived[Product, Long]
val transactor = TransactorZIO.fromUrl("jdbc:postgresql://localhost/shop", SqlDialect.PostgreSQL)
// Batch insert, then query with a custom filter
val program = transactor.transact:
repo.insertAll(List(
Product(1L, "Widget", 9.99),
Product(2L, "Gadget", 29.99)
))
sql"SELECT * FROM product WHERE price < ${15.0}".query[Product]
These six follow the learning path, from installing the library to a small working backend. The guides index on the website lists every tutorial, how-to guide, migration guide and deep dive.
Full API Reference
Every block in the catalog above links to its own reference page. The blocks
large enough to have several pages start from an overview:
Schema - core type system, dynamic values, optics, validation, and schema evolution
评论