zio.blocks.schema

Schemas of Scala types and what is built on them: codecs, dynamic values, optics, patches and migrations. Importing the package with import zio.blocks.schema._ also brings in the extension syntax (toJsonString, fromJson, diff, ...) and the p"..." path interpolator.

On Scala 3 the path interpolator is an extension method named p, so with both import zio.blocks.schema._ and import zio.blocks.html._ in scope a call to the HTML element p(...) is ambiguous. Write that element as zio.blocks.html.p(...), or import only the names you need from one of the two packages.

Attributes

See also

Members list

Type members

Classlikes

trait As[A, B] extends Into[A, B]

Bidirectional conversion between types A and B.

Bidirectional conversion between types A and B.

As[A, B] extends Into[A, B], so it can be used anywhere an Into is expected. Use reverse to get an As[B, A] that reverses the direction.

For As[A, B] to be derivable, the bidirectional conversion must be compatible:

Compatibility Rules:

  • Field mappings must be consistent: The same field correspondence in both directions
  • Coercions must be invertible with runtime validation (Int ↔ Long, Float ↔ Double, etc.)
  • Optional fields: Can add optional fields in one direction (becomes None in reverse)
  • Default values: Allowed only on fields that exist in both types. Fields with defaults that don't exist in the other type break round-trip guarantee.
  • Collection types: Can convert between different collection types (may be lossy for Set/List conversions)

Attributes

Companion
object
Source
As.scala
Supertypes
trait Into[A, B]
class Object
trait Matchable
class Any

Attributes

Companion
trait
Source
As.scala
Supertypes
class Object
trait Matchable
class Any
Self type
As.type

Attributes

Source
As.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object As

Attributes

Source
AsVersionSpecific.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object As
case object BuildInfo

This object was generated by sbt-buildinfo.

This object was generated by sbt-buildinfo.

Attributes

Source
BuildInfo.scala
Supertypes
trait Singleton
trait Product
trait Mirror
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
Self type
BuildInfo.type

Scala 3 only: derives a CompanionClass for a companion object type with a macro. It fails to compile for a type that has no companion class.

Scala 3 only: derives a CompanionClass for a companion object type with a macro. It fails to compile for a type that has no companion class.

Attributes

Companion
trait
Source
DerivedOptics.scala
Supertypes
class Object
trait Matchable
class Any
Self type
trait CompanionClass[A]

Scala 3 only: a type class that gives the class whose companion object has the type A. For Book.type, the type of the companion object, Type is Book.

Scala 3 only: a type class that gives the class whose companion object has the type A. For Book.type, the type of the companion object, Type is Book.

Attributes

Companion
object
Source
DerivedOptics.scala
Supertypes
class Object
trait Matchable
class Any
transparent trait CompanionOptics[S]

Mix this trait into a companion object to build optics for S from a selector lambda: $(_.title), or the same with a name, optic(_.title). A macro reads the lambda at compile time and builds the optic from the implicit Schema[S]. The kind of optic follows from the path: a Lens when every step is a field, a Prism when every step is when, a Traversal when any step is each, eachKey, eachValue, atIndices, atKeys or searchFor, and an Optional otherwise.

Mix this trait into a companion object to build optics for S from a selector lambda: $(_.title), or the same with a name, optic(_.title). A macro reads the lambda at compile time and builds the optic from the implicit Schema[S]. The kind of optic follows from the path: a Lens when every step is a field, a Prism when every step is when, a Traversal when any step is each, eachKey, eachValue, atIndices, atKeys or searchFor, and an Optional otherwise.

A path is a chain of these steps:

  • .field: a field of a record;
  • .when[C]: the case C of a variant;
  • .at(i), .atIndices(i, j), .each: elements of a sequence;
  • .atKey(k), .atKeys(k1, k2), .eachKey, .eachValue: keys and values of a map;
  • .wrapped[B]: the value of type B inside a wrapper;
  • .searchFor[T]: every value at or below this point that decodes as a T (needs an implicit Schema[T]; modify skips map keys).

On Scala 3, a path can also select a tuple element by index, as in $(_(0)), and when also takes a case of a union type. The step methods compile only inside $ and optic, and any other expression in the lambda is a compile error.

The macro checks the path against the types, and the schema is checked when the optic is built: if the schema at a step has another shape than the step needs, for example a .field step where the schema is a wrapper built with Schema#transform, building the optic throws a RuntimeException such as Expected a record.

sealed trait Format
case class Paperback(pages: Int) extends Format
case class Ebook(sizeMb: Double) extends Format

case class Book(title: String, tags: List[String], format: Format)
object Book extends CompanionOptics[Book] {
 implicit val schema: Schema[Book] = Schema.derived
 val title: Lens[Book, String]     = $(_.title)
 val pages: Optional[Book, Int]    = $(_.format.when[Paperback].pages)
 val tags: Traversal[Book, String] = optic(_.tags.each)
}

val zionomicon = Book("Zionomicon", List("zio", "scala"), Paperback(870))
Book.pages.getOption(zionomicon)   // Some(870)
Book.pages.toString              // Optional(_.format.when[Paperback].pages)

Attributes

See also
Source
CompanionOptics.scala
Supertypes
class Object
trait Matchable
class Any

Mix this trait into the companion object of a case class or a sealed trait to get the class's optics without writing them: a Lens for each field of a case class, named after the field, and a Prism for each case of a sealed trait (or, on Scala 3, an enum), named after the case with its first letter in lower case (Paperback gives paperback). They are the members of optics. On Scala 3 they are also members of the companion itself (Book.title), through a given conversion. A member that the companion defines itself takes precedence there, and the derived optic stays available on optics. Direct access goes through an implicit conversion, so Scala 3 gives a feature warning at each use unless scala.language.implicitConversions is imported, as the first example does.

Mix this trait into the companion object of a case class or a sealed trait to get the class's optics without writing them: a Lens for each field of a case class, named after the field, and a Prism for each case of a sealed trait (or, on Scala 3, an enum), named after the case with its first letter in lower case (Paperback gives paperback). They are the members of optics. On Scala 3 they are also members of the companion itself (Book.title), through a given conversion. A member that the companion defines itself takes precedence there, and the derived optic stays available on optics. Direct access goes through an implicit conversion, so Scala 3 gives a feature warning at each use unless scala.language.implicitConversions is imported, as the first example does.

An implicit Schema of the class must be in scope where optics is used; a schema defined in the companion is. For a type that is not the class of a companion, such as Box[Int] or a type alias, use DerivedOptics.Of. On Scala 3, a value class whose schema is a wrapper (built with transform) gets a working lens only when its field is named value. Opaque types are not supported yet.

The optics are built the first time optics is evaluated and kept in a global cache keyed by the type's printed name. Every companion for the same type shares the optics built from the first schema used, and so do different types that print the same, such as two local classes named Book in different methods: the second then fails with a ClassCastException or No optic found (a bug, see docs/dev/issues.md).

A known problem, described in docs/dev/issues.md: on Scala 2, optics compiles only inside the zio.blocks.schema package, so the examples below are compiled on Scala 3 only.

// scala-3-only
import scala.language.implicitConversions

case class Book(title: String, pages: Int)
object Book extends DerivedOptics {
 implicit val schema: Schema[Book] = Schema.derived
}

val title: Lens[Book, String] = Book.optics.title
val pages: Lens[Book, Int]    = Book.pages // direct access, Scala 3 only
// scala-3-only
sealed trait Format
case class Paperback(pages: Int) extends Format
case class Ebook(sizeMb: Double) extends Format
object Format extends DerivedOptics {
 implicit val schema: Schema[Format] = Schema.derived
}

val paperback: Prism[Format, Paperback] = Format.optics.paperback
// scala-3-only
case class PageCount(value: Int) extends AnyVal
object PageCount extends DerivedOptics {
 // a wrapper schema, built with `transform`
 implicit val schema: Schema[PageCount] = Schema[Int].transform(PageCount(_), _.value)
}

val value: Lens[PageCount, Int] = PageCount.optics.value

Attributes

See also
Companion
object
Source
DerivedOptics.scala
Supertypes
class Object
trait Matchable
class Any
object DerivedOptics

Holds DerivedOptics.Of and the runtime helpers that the optics macros call.

Holds DerivedOptics.Of and the runtime helpers that the optics macros call.

Attributes

Companion
trait
Source
DerivedOptics.scala
Supertypes
class Object
trait Matchable
class Any
Self type
case class DynamicOptic(nodes: IndexedSeq[Node])

An untyped path into a value: a sequence of DynamicOptic.Node steps, such as a field, a case, an index, a map key or every element. A typed Optic turns into one with Optic#toDynamic. The DynamicValue operations (get, modify, set, delete, insert) take one, Reflect#get navigates a schema with one, and SchemaError and OpticCheck use them to say where a problem is.

An untyped path into a value: a sequence of DynamicOptic.Node steps, such as a field, a case, an index, a map key or every element. A typed Optic turns into one with Optic#toDynamic. The DynamicValue operations (get, modify, set, delete, insert) take one, Reflect#get navigates a schema with one, and SchemaError and OpticCheck use them to say where a problem is.

Build a path from DynamicOptic.root with the builder methods, or with the p"..." interpolator, which checks the syntax at compile time. toString renders the path in the interpolator syntax (.books[0].title), and toScalaString in the syntax of the optic macros (.books.at(0).title), which error messages use. The companion's schema makes paths serializable.

val path = DynamicOptic.root.field("books").at(0).field("title")

path.toString              // .books[0].title
path.toScalaString         // .books.at(0).title
path == p".books[0].title" // true

Attributes

See also
Companion
object
Source
DynamicOptic.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object DynamicOptic

The starting points for paths, their DynamicOptic.Node steps, and the schemas that make paths serializable.

The starting points for paths, their DynamicOptic.Node steps, and the schemas that make paths serializable.

Attributes

Companion
class
Source
DynamicOptic.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
final case class DynamicSchema(reflect: Reflect[NoBinding, _])

A type-erased schema representation that can validate DynamicValue instances at runtime.

A type-erased schema representation that can validate DynamicValue instances at runtime.

DynamicSchema wraps an unbound Reflect structure (one with no runtime binding), enabling schema-based validation and manipulation without compile-time type information. This is useful for scenarios where schemas are loaded dynamically, such as from configuration files, databases, or network services.

Key capabilities:

  • '''Validation''': Check whether a DynamicValue conforms to this schema's structure and constraints using check or conforms
  • '''Schema Conversion''': Convert to a Schema[DynamicValue] that only accepts conforming values via toSchema
  • '''Metadata Access''': Access documentation, type names, modifiers, defaults, and examples
  • '''Structure Navigation''': Navigate the schema structure using DynamicOptic paths

Value parameters

reflect

The underlying unbound reflect structure representing the schema

Attributes

See also

Schema.toDynamicSchema for creating a DynamicSchema from a typed Schema

DynamicValue for the runtime value representation

Example
import zio.blocks.chunk.Chunk
case class Person(name: String, age: Int)
// Create a DynamicSchema from an existing Schema
val personSchema: Schema[Person] = Schema.derived[Person]
val dynamicSchema: DynamicSchema = personSchema.toDynamicSchema
// Validate a DynamicValue against the schema
val value = DynamicValue.Record(Chunk(
 "name" -> DynamicValue.Primitive(PrimitiveValue.String("Alice")),
 "age" -> DynamicValue.Primitive(PrimitiveValue.Int(30))
))
dynamicSchema.check(value) // None if valid, Some(SchemaError) if invalid
dynamicSchema.conforms(value) // true if valid
Companion
object
Source
DynamicSchema.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object DynamicSchema extends TypeIdSchemas

Attributes

Companion
class
Source
DynamicSchema.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Show all
Self type

Attributes

Companion
trait
Source
DynamicSchemaExpr.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
sealed trait DynamicSchemaExpr

Attributes

Companion
object
Source
DynamicSchemaExpr.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object DynamicValue

Attributes

Companion
trait
Source
DynamicValue.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
sealed trait DynamicValue

A schema-less, dynamically-typed representation of any value.

A schema-less, dynamically-typed representation of any value.

DynamicValue provides a universal data model that can represent any structured value without requiring compile-time type information. It serves as an intermediate representation for serialization, schema evolution, data transformation, and cross-format conversion.

The ADT consists of six cases:

Navigation and modification use DynamicOptic, a path-based lens system for traversing and updating nested structures.

Attributes

See also

Schema.toDynamicValue for converting typed values to DynamicValue

Schema.fromDynamicValue for converting DynamicValue back to typed values

DynamicOptic for path-based navigation

Companion
object
Source
DynamicValue.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class Map
object Null
class Primitive
class Record
class Sequence
class Variant
Show all

Attributes

Companion
trait
Source
DynamicValueMergeStrategy.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type

Strategy for merging two DynamicValue structures.

Strategy for merging two DynamicValue structures.

A DynamicValueMergeStrategy is a function (DynamicOptic, DynamicValue, DynamicValue) => DynamicValue that determines how to merge two DynamicValue values at a given path. The recurse method controls whether the merge driver should descend into containers (Record/Sequence/Map) or call apply directly.

When recurse returns true for a container type:

  • Records are merged by field name (union of fields, recursive merge on shared fields)
  • Sequences are merged by index (union of indices, recursive merge on shared indices)
  • Maps are merged by key (union of keys, recursive merge on shared keys)
  • Variants with same case name merge inner values; different cases: right wins

When recurse returns false, apply is called with the container values directly.

Attributes

Companion
object
Source
DynamicValueMergeStrategy.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Auto
object Concat
class Custom
object KeepLeft
object Replace
object Shallow
Show all

Attributes

Companion
class
Source
DynamicValueSelection.scala
Supertypes
class Object
trait Matchable
class Any
Self type
final case class DynamicValueSelection(either: Either[SchemaError, Chunk[DynamicValue]]) extends AnyVal

A wrapper around Either[SchemaError, Chunk[DynamicValue]] that provides fluent chaining for DynamicValue navigation and querying operations.

A wrapper around Either[SchemaError, Chunk[DynamicValue]] that provides fluent chaining for DynamicValue navigation and querying operations.

DynamicValueSelection enables a fluent API style for navigating through DynamicValue structures:

val dv = DynamicValue.Record(
 "users" -> DynamicValue.Sequence(
   DynamicValue.Record("name" -> DynamicValue.string("Alice"))
 )
)

val names: DynamicValueSelection =
 dv.get("users").sequences.apply(0).get("name").primitives

The selection can contain zero, one, or multiple DynamicValue values, supporting both single-value navigation and multi-value queries.

Attributes

Companion
object
Source
DynamicValueSelection.scala
Supertypes
trait Serializable
trait Product
trait Equals
class AnyVal
trait Matchable
class Any
Show all

Attributes

Companion
trait
Source
DynamicValueType.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
sealed trait DynamicValueType extends DynamicValue => Boolean

A sealed trait representing the type of a DynamicValue.

A sealed trait representing the type of a DynamicValue.

This is used by DynamicValueMergeStrategy to make decisions about recursion without needing access to the actual DynamicValue values.

Each case provides two type members:

  • Type: The corresponding DynamicValue subtype (e.g., DynamicValue.Record)
  • Unwrap: The underlying Scala type of the value (e.g., Chunk[(String, DynamicValue)])

Attributes

Companion
object
Source
DynamicValueType.scala
Supertypes
trait DynamicValue => Boolean
class Object
trait Matchable
class Any
Known subtypes
object Map
object Null
object Primitive
object Record
object Sequence
object Variant
Show all

Attributes

Companion
trait
Source
Into.scala
Supertypes
class Object
trait Matchable
class Any
Show all
Self type
Into.type
trait Into[-A, +B]

Attributes

Companion
object
Source
Into.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
trait As[A, B]

Attributes

Source
Into.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Into

Attributes

Source
Into.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Into

Attributes

Source
IntoVersionSpecific.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Into
object IsCollection

Attributes

Companion
trait
Source
IsCollection.scala
Supertypes
class Object
trait Matchable
class Any
Self type
trait IsCollection[A]

Attributes

Companion
object
Source
IsCollection.scala
Supertypes
class Object
trait Matchable
class Any
object IsIntegral

Attributes

Companion
trait
Source
IsIntegral.scala
Supertypes
class Object
trait Matchable
class Any
Self type
IsIntegral.type
sealed trait IsIntegral[A]

Type class for integral types that support bitwise operations. Only Byte, Short, Int, and Long are supported.

Type class for integral types that support bitwise operations. Only Byte, Short, Int, and Long are supported.

Attributes

Companion
object
Source
IsIntegral.scala
Supertypes
class Object
trait Matchable
class Any
object IsMap

Attributes

Companion
trait
Source
IsMap.scala
Supertypes
class Object
trait Matchable
class Any
Self type
IsMap.type
trait IsMap[MapKV]

Attributes

Companion
object
Source
IsMap.scala
Supertypes
class Object
trait Matchable
class Any
sealed trait IsNumeric[A]

Type class for numeric types that support arithmetic operations.

Type class for numeric types that support arithmetic operations.

Note: Consider using NumericPrimitiveType directly for new code, which is part of the sealed PrimitiveType hierarchy and fully serializable.

Attributes

Companion
object
Source
IsNumeric.scala
Supertypes
class Object
trait Matchable
class Any
object IsNumeric

Attributes

Companion
trait
Source
IsNumeric.scala
Supertypes
class Object
trait Matchable
class Any
Self type
IsNumeric.type
sealed trait Lazy[+A]

A Lazy[A] is a computation of an A that runs when force is first called. The schema module uses it where parts of a structure must refer to parts that are not built yet, as in a recursive type: the methods of a ReflectTransformer return their nodes as Lazy values, and type class derivation pairs the binding of each node with a Lazy instance.

A Lazy[A] is a computation of an A that runs when force is first called. The schema module uses it where parts of a structure must refer to parts that are not built yet, as in a recursive type: the methods of a ReflectTransformer return their nodes as Lazy values, and type class derivation pairs the binding of each node with a Lazy instance.

map, flatMap and the other combinators build a new Lazy without running anything. force runs the whole chain with an explicit stack, so a long chain does not overflow the stack, and caches the result, or the exception, in the Lazy it is called on. The cache belongs to that instance: a Lazy that is part of another one's chain runs its computation again when the other one is forced, even if it was forced before.

var evaluations = 0
val title: Lazy[String] = Lazy {
 evaluations += 1
 "Zionomicon"
}

val before = title.isEvaluated // false
val first  = title.force       // Zionomicon
val second = title.force       // Zionomicon
val after  = (title.isEvaluated, evaluations) // (true,1)

Attributes

See also
Companion
object
Source
Lazy.scala
Supertypes
class Object
trait Matchable
class Any
object Lazy

Constructors for Lazy.

Constructors for Lazy.

Attributes

Companion
trait
Source
Lazy.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Lazy.type
sealed trait Lens[S, A] extends Optic[S, A]

A lens focuses on a part of S that is always there, such as a field of a case class, or a field of a field. Use it to read or replace that part without rebuilding the record by hand. A lens never reports a missing focus: check always returns None, modifyOption always returns Some, and modifyOrFail always returns Right.

A lens focuses on a part of S that is always there, such as a field of a case class, or a field of a field. Use it to read or replace that part without rebuilding the record by hand. A lens never reports a missing focus: check always returns None, modifyOption always returns Some, and modifyOrFail always returns Right.

Get a lens from the $ macro of CompanionOptics, from DerivedOptics, from Reflect.Record#lensByName, or with the Lens.apply constructor.

case class Book(title: String, year: Int)
object Book extends CompanionOptics[Book] {
 implicit val schema: Schema[Book] = Schema.derived
 val year: Lens[Book, Int] = $(_.year)
}

val zionomicon = Book("Zionomicon", 2021)
Book.year.get(zionomicon)          // 2021
Book.year.replace(zionomicon, 2024) // Book(Zionomicon,2024)

Attributes

See also
Companion
object
Source
Optic.scala
Supertypes
trait Optic[S, A]
class Object
trait Matchable
class Any
object Lens

Constructors for Lens.

Constructors for Lens.

Attributes

Companion
trait
Source
Optic.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Lens.type
sealed trait Modifier extends StaticAnnotation

A Modifier is metadata on a schema, or on one of its fields or cases, that codecs and other derivations read: it renames a field in JSON, accepts an old name, leaves a field out, or carries format-specific configuration. Modifiers are plain data with schemas of their own, so they can be serialized together with a schema.

A Modifier is metadata on a schema, or on one of its fields or cases, that codecs and other derivations read: it renames a field in JSON, accepts an old name, leaves a field out, or carries format-specific configuration. Modifiers are plain data with schemas of their own, so they can be serialized together with a schema.

Every modifier is also an annotation. Schema.derived reads Modifier.Term annotations on fields and cases, and Modifier.Reflect annotations on the type. To leave the type unannotated, add them with Schema#modifier for the type, or with DerivationBuilder#modifier or Deriver#withModifier for one derivation.

Which modifiers a codec reads depends on its format: the JSON codec reads all the built-in ones except id and config, while the Avro and MessagePack codecs, for example, ignore transient, rename and alias.

case class Book(
 @Modifier.rename("name") title: String,
 @Modifier.alias("published") year: Int,
 @Modifier.transient() notes: String = ""
)
object Book {
 implicit val schema: Schema[Book] = Schema.derived
}

val json = Book("Zionomicon", 2021, "signed copy").toJsonString
// {"name":"Zionomicon","year":2021}
val book = """{"name":"Zionomicon","published":2021}""".fromJson[Book]
// Right(Book(Zionomicon,2021,))

Attributes

See also
Companion
object
Source
Modifier.scala
Supertypes
trait StaticAnnotation
class Annotation
class Object
trait Matchable
class Any
Known subtypes
trait Reflect
class caseNaming
class config
class fieldNaming
trait Term
class alias
class id
class rename
class transient
Show all
object Modifier

The built-in modifiers and their schemas.

The built-in modifiers and their schemas.

Attributes

Companion
trait
Source
Modifier.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Modifier.type
sealed trait NameMapper extends String => String

A sealed trait that represents a generic contract for mapping string input to string output. Classes or objects that extend NameMapper provide an implementation of the apply method, which specifies how a string transformation is applied. This transformation can be used for enforcing naming conventions or other string-based manipulations.

A sealed trait that represents a generic contract for mapping string input to string output. Classes or objects that extend NameMapper provide an implementation of the apply method, which specifies how a string transformation is applied. This transformation can be used for enforcing naming conventions or other string-based manipulations.

Attributes

Companion
object
Source
NameMapper.scala
Supertypes
trait String => String
class Object
trait Matchable
class Any
Known subtypes
object CamelCase
class Custom
object Identity
object KebabCase
object PascalCase
object SnakeCase
Show all
object NameMapper

The NameMapper object provides a set of predefined strategies for transforming string names into common naming conventions, such as snake_case, camelCase, PascalCase, and kebab-case. Additionally, it allows for custom transformations via the Custom case class.

The NameMapper object provides a set of predefined strategies for transforming string names into common naming conventions, such as snake_case, camelCase, PascalCase, and kebab-case. Additionally, it allows for custom transformations via the Custom case class.

This object defines several NameMapper implementations:

  • SnakeCase: Transforms strings to snake_case (e.g., "exampleName" → "example_name").
  • CamelCase: Transforms strings to camelCase (e.g., "example_name" → "exampleName").
  • PascalCase: Transforms strings to PascalCase (e.g., "example_name" → "ExampleName").
  • KebabCase: Transforms strings to kebab-case (e.g., "exampleName" → "example-name").
  • Identity: Returns the input string as-is, performing no transformation.
  • Custom: Allows for user-defined transformations by applying a given function to the input string.

Attributes

Companion
trait
Source
NameMapper.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
NameMapper.type
sealed trait NumericPrimitiveType[A] extends PrimitiveType[A]

Sub-trait of PrimitiveType for numeric types that support arithmetic operations. Provides access to the Scala Numeric type class for the underlying type.

Sub-trait of PrimitiveType for numeric types that support arithmetic operations. Provides access to the Scala Numeric type class for the underlying type.

This trait is sealed within the PrimitiveType hierarchy - all implementations are the numeric case classes (Byte, Short, Int, Long, Float, Double, BigInt, BigDecimal).

Attributes

Source
PrimitiveType.scala
Supertypes
trait PrimitiveType[A]
class Object
trait Matchable
class Any
Known subtypes
class BigDecimal
class BigInt
class Byte
class Double
class Float
class Int
class Long
class Short
Show all
sealed trait Optic[S, A]

An optic is a first-class path into a value of type S that focuses on parts of type A. It reads, replaces and modifies those parts without rebuilding the enclosing value by hand. It also carries the schemas of both ends (source and focus), so a failed access can say where and why it failed, and the path can be turned into a DynamicOptic or a SchemaExpr query.

An optic is a first-class path into a value of type S that focuses on parts of type A. It reads, replaces and modifies those parts without rebuilding the enclosing value by hand. It also carries the schemas of both ends (source and focus), so a failed access can say where and why it failed, and the path can be turned into a DynamicOptic or a SchemaExpr query.

Every optic is one of four kinds:

  • Lens: a part that is always there, such as a field of a case class;
  • Prism: one case of a sealed trait or enum;
  • Optional: a part that may be missing, such as a field inside one case, the element at an index or the value at a map key;
  • Traversal: zero or more parts, such as every element of a collection.

Get optics from the $ (or optic) macro of CompanionOptics, or from the optics member of DerivedOptics. Compose them with apply. Two lenses give a lens, two prisms give a prism, anything composed with a traversal gives a traversal, and every other pair gives an optional.

This trait has the operations that every kind supports: modify, modifyOption, modifyOrFail, check and toDynamic, plus operators such as ===, >, + and && that build a SchemaExpr. Reading and replacing depend on the kind: get and replace on Lens, getOption and replace on Prism and Optional, and fold on Traversal.

case class Author(name: String)
case class Book(title: String, author: Author)
object Book extends CompanionOptics[Book] {
 implicit val schema: Schema[Book] = Schema.derived
 val authorName: Lens[Book, String] = $(_.author.name)
}

val zionomicon = Book("Zionomicon", Author("John A. De Goes"))
Book.authorName.modify(zionomicon, _.toUpperCase) // Book(Zionomicon,Author(JOHN A. DE GOES))
Book.authorName.toDynamic.toString                 // .author.name

Type parameters

A

the type of the parts it focuses on

S

the type of the value the optic reads from and updates

Attributes

See also
Source
Optic.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
trait Lens[S, A]
trait Optional[S, A]
trait Prism[S, A]
trait Traversal[S, A]
Self type
Optic[S, A]
object OpticCheck

The problems that an OpticCheck can hold.

The problems that an OpticCheck can hold.

Attributes

Companion
class
Source
OpticCheck.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
OpticCheck.type
final case class OpticCheck(errors: ::[Single]) extends Exception, NoStackTrace

The reason an optic could not reach its focus. The *OrFail methods of Optic return it in a Left, Optic#check returns it, and so does SchemaExpr#eval when evaluation fails.

The reason an optic could not reach its focus. The *OrFail methods of Optic return it in a Left, Optic#check returns it, and so does SchemaExpr#eval when evaluation fails.

It holds one or more problems (OpticCheck.Single). Each one is an error (OpticCheck.Error: another case of a variant, a failing wrapper, a failed conversion) or a warning (OpticCheck.Warning: an empty collection, an index past the end, a missing key). Each problem carries the path of the whole optic and the path up to the step where it was found, rendered in its message with DynamicOptic#toScalaString:

During attempted access at .tags.at(0), encountered a sequence out of bounds at .tags.at(0): index is 0, but size is 0

An OpticCheck is also an exception without a stack trace, whose message is message.

Attributes

See also
Companion
object
Source
OpticCheck.scala
Supertypes
trait Product
trait Equals
trait NoStackTrace
class Exception
class Throwable
trait Serializable
class Object
trait Matchable
class Any
Show all
trait OpticsFor[S]

Type class that provides derived optics for type S. Used internally to enable the given Conversion pattern for direct field access.

Type class that provides derived optics for type S. Used internally to enable the given Conversion pattern for direct field access.

It is public because Scala 3.10 only finds givens in a type's companion that are accessible where the search happens: with private[schema], Person.name stops compiling outside the zio.blocks.schema package.

Attributes

Companion
object
Source
DerivedOptics.scala
Supertypes
class Object
trait Matchable
class Any
object OpticsFor

Attributes

Companion
trait
Source
DerivedOptics.scala
Supertypes
class Object
trait Matchable
class Any
Self type
OpticsFor.type
final class OpticsHolder(members: Map[String, Any]) extends Dynamic, Selectable

The runtime object behind optics: it holds the derived optics by name, and the type of optics gives each member its type. It is an implementation detail; use the members of optics. On Scala 2 it is DerivedOptics.OpticsHolder and backs only the optics of types that are neither case classes nor sealed traits (the others are anonymous classes); on Scala 3 it is zio.blocks.schema.OpticsHolder, backs every optics, and is also a Selectable.

The runtime object behind optics: it holds the derived optics by name, and the type of optics gives each member its type. It is an implementation detail; use the members of optics. On Scala 2 it is DerivedOptics.OpticsHolder and backs only the optics of types that are neither case classes nor sealed traits (the others are anonymous classes); on Scala 3 it is zio.blocks.schema.OpticsHolder, backs every optics, and is also a Selectable.

Attributes

Source
DerivedOptics.scala
Supertypes
trait Selectable
trait Dynamic
class Object
trait Matchable
class Any
object Optional

Constructors for Optional: compositions of two optics that give an optional, and optionals on an index, a map key or a wrapped value.

Constructors for Optional: compositions of two optics that give an optional, and optionals on an index, a map key or a wrapped value.

Attributes

Companion
trait
Source
Optic.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Optional.type
sealed trait Optional[S, A] extends Optic[S, A]

An optional focuses on a part of S that may be missing: a field inside one case of a variant, the element at an index of a sequence, the value at a key of a map, or the value inside a wrapper. Composing a Lens with a Prism, in either order, gives an optional.

An optional focuses on a part of S that may be missing: a field inside one case of a variant, the element at an index of a sequence, the value at a key of a map, or the value inside a wrapper. Composing a Lens with a Prism, in either order, gives an optional.

When the part is missing, getOption returns None, and replace and modify return a value equal to s. The *OrFail methods say why in an OpticCheck: another case (OpticCheck.UnexpectedCase), an index past the end (OpticCheck.SequenceIndexOutOfBounds), a missing key (OpticCheck.MissingKey), or a wrapper whose wrap or unwrap throws a SchemaError (OpticCheck.WrappingError). replace never adds a missing element or key.

case class Book(title: String, tags: List[String])
object Book extends CompanionOptics[Book] {
 implicit val schema: Schema[Book] = Schema.derived
 val firstTag: Optional[Book, String] = $(_.tags.at(0))
}

Book.firstTag.getOption(Book("Zionomicon", List("zio", "scala"))) // Some(zio)
Book.firstTag.getOption(Book("Zionomicon", Nil))                  // None

Attributes

See also
Companion
object
Source
Optic.scala
Supertypes
trait Optic[S, A]
class Object
trait Matchable
class Any

Adds the p"..." interpolator, which turns a path literal into a DynamicOptic at compile time. The package object zio.blocks.schema mixes this trait in, so import zio.blocks.schema._ brings p into scope.

Adds the p"..." interpolator, which turns a path literal into a DynamicOptic at compile time. The package object zio.blocks.schema mixes this trait in, so import zio.blocks.schema._ brings p into scope.

Attributes

Source
PathInterpolator.scala
Supertypes
class Object
trait Matchable
class Any
object PathMacros

Macro implementation of the p"..." interpolator: it parses the literal with PathParser and builds the DynamicOptic expression.

Macro implementation of the p"..." interpolator: it parses the literal with PathParser and builds the DynamicOptic expression.

Attributes

Source
PathMacros.scala
Supertypes
class Object
trait Matchable
class Any
Self type
PathMacros.type
trait Platform

Platform detection for zio-blocks-schema.

Platform detection for zio-blocks-schema.

This trait provides compile-time information about the current runtime platform. Some features (like structural types) require reflection APIs that are only available on the JVM.

Platform-specific implementations are provided in:

  • jvm/src/main/scala/zio/blocks/schema/PlatformSpecific.scala
  • js/src/main/scala/zio/blocks/schema/PlatformSpecific.scala

Attributes

Companion
object
Source
Platform.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Platform
object Platform extends PlatformSpecific

Attributes

Companion
trait
Source
Platform.scala
Supertypes
trait Platform
class Object
trait Matchable
class Any
Self type
Platform.type
trait PlatformSpecific extends Platform

JVM-specific platform implementation.

JVM-specific platform implementation.

Attributes

Source
PlatformSpecific.scala
Supertypes
trait Platform
class Object
trait Matchable
class Any
Known subtypes
object Platform
sealed trait PrimitiveType[A]

One of the scalar types that a Reflect.Primitive node stands for: Unit, Boolean, the numeric types, Char, String, the java.time types, java.util.Currency and java.util.UUID. Each case converts its type to and from DynamicValue and carries a Validation of its values.

One of the scalar types that a Reflect.Primitive node stands for: Unit, Boolean, the numeric types, Char, String, the java.time types, java.util.Currency and java.util.UUID. Each case converts its type to and from DynamicValue and carries a Validation of its values.

Only DynamicSchema#check checks the validation: fromDynamicValue and Reflect#fromDynamicValue accept values that break it.

Attributes

See also
Companion
object
Source
PrimitiveType.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class BigDecimal
class BigInt
class Byte
class Double
class Float
class Int
class Long
class Short
class Boolean
class Char
class Currency
class DayOfWeek
class Duration
class Instant
class LocalDate
class LocalTime
class Month
class MonthDay
class OffsetTime
class Period
class String
class UUID
object Unit
class Year
class YearMonth
class ZoneId
class ZoneOffset
Show all
object PrimitiveType

The primitive types, one case per Scala or Java type.

The primitive types, one case per Scala or Java type.

Attributes

Companion
trait
Source
PrimitiveType.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type

The cases of PrimitiveValue, their ordering and their schemas.

The cases of PrimitiveValue, their ordering and their schemas.

Attributes

Companion
trait
Source
PrimitiveValue.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
sealed trait PrimitiveValue

A PrimitiveValue is a scalar value inside a DynamicValue, which DynamicValue.Primitive wraps. There is one case per PrimitiveType, and each case keeps the exact Scala or Java type of its value: Int(2021) and Long(2021L) are different values.

A PrimitiveValue is a scalar value inside a DynamicValue, which DynamicValue.Primitive wraps. There is one case per PrimitiveType, and each case keeps the exact Scala or Java type of its value: Int(2021) and Long(2021L) are different values.

Primitive values are ordered: two values of the same case by their value, and values of different cases by the order of the cases, from Unit to UUID (see typeIndex). PrimitiveValue.ordering and DynamicValue#compare use this order. Int values are compared by subtraction, which overflows, so two Int values that are more than Int.MaxValue apart compare the wrong way round.

val title = PrimitiveValue.String("Zionomicon")
val year  = PrimitiveValue.Int(2021)

val kind   = year.primitiveType                       // Int(None)
val before = year < PrimitiveValue.Int(2024)          // true
val sorted = List[PrimitiveValue](title, year).sorted // List(Int(2021), String(Zionomicon))
val value  = DynamicValue.Primitive(title)            // "Zionomicon"

Attributes

See also
Companion
object
Source
PrimitiveValue.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class BigDecimal
class BigInt
class Boolean
class Byte
class Char
class Currency
class DayOfWeek
class Double
class Duration
class Float
class Instant
class Int
class LocalDate
class LocalTime
class Long
class Month
class MonthDay
class OffsetTime
class Period
class Short
class String
class UUID
object Unit
class Year
class YearMonth
class ZoneId
class ZoneOffset
Show all
object Prism

Constructors for Prism.

Constructors for Prism.

Attributes

Companion
trait
Source
Optic.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Prism.type
sealed trait Prism[S, A <: S] extends Optic[S, A]

A prism focuses on one case A of a sealed trait, enum or other variant S. On a value of another case, getOption returns None, and replace and modify return the value unchanged. The *OrFail methods return an OpticCheck.UnexpectedCase instead, which names the expected and the actual case.

A prism focuses on one case A of a sealed trait, enum or other variant S. On a value of another case, getOption returns None, and replace and modify return the value unchanged. The *OrFail methods return an OpticCheck.UnexpectedCase instead, which names the expected and the actual case.

sealed trait Format
case class Paperback(pages: Int) extends Format
case class Ebook(sizeMb: Double) extends Format
object Format extends CompanionOptics[Format] {
 implicit val schema: Schema[Format] = Schema.derived
 val paperback: Prism[Format, Paperback] = $(_.when[Paperback])
}

Format.paperback.getOption(Paperback(870))  // Some(Paperback(870))
Format.paperback.getOption(Ebook(5.2))      // None
Format.paperback.reverseGet(Paperback(870)) // Paperback(870), typed as a Format

Attributes

See also
Companion
object
Source
Optic.scala
Supertypes
trait Optic[S, A]
class Object
trait Matchable
class Any
final class RebindException(val path: DynamicOptic, val typeId: TypeId[_ <: AnyKind], val expectedKind: String) extends RuntimeException

Thrown by DynamicSchema#rebind when its BindingResolver has no binding for a type in the schema. For a node behind a Reflect.Deferred, such as the recursive field of a recursive type, it is thrown later, when that part of the rebound schema is first used. The message names the kind of binding, the full name of the type and the path.

Thrown by DynamicSchema#rebind when its BindingResolver has no binding for a type in the schema. For a node behind a Reflect.Deferred, such as the recursive field of a recursive type, it is thrown later, when that part of the rebound schema is first used. The message names the kind of binding, the full name of the type and the path.

Value parameters

expectedKind

the kind of binding that was looked up: Record, Variant, Sequence, Map, Dynamic, Primitive or Wrapper

path

the location of the node that needs the binding (a wrapped node has the path of its wrapper)

typeId

the type ID that has no binding

Attributes

Source
RebindTransformer.scala
Supertypes
class Exception
class Throwable
trait Serializable
class Object
trait Matchable
class Any
Show all
object Reflect

The kinds of Reflect node, the Reflect.Bound and Reflect.Unbound aliases, and the nodes of the built-in primitive, option, either, collection and map types.

The kinds of Reflect node, the Reflect.Bound and Reflect.Unbound aliases, and the nodes of the built-in primitive, option, either, collection and map types.

Attributes

Companion
trait
Source
Reflect.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Reflect.type
sealed trait Reflect[F[_, _], A] extends Reflectable[A]

A Reflect[F, A] is the tree that describes the structure of the type A. Each node describes one type: it holds the type's TypeId, documentation, modifiers, an optional default value and examples, and the child nodes for its fields, cases, elements, keys or values. A Schema wraps one, which Schema#reflect returns.

A Reflect[F, A] is the tree that describes the structure of the type A. Each node describes one type: it holds the type's TypeId, documentation, modifiers, an optional default value and examples, and the child nodes for its fields, cases, elements, keys or values. A Schema wraps one, which Schema#reflect returns.

There are eight kinds of node:

F is what each node holds besides its structure. In a Reflect.Bound, where F is Binding, each node holds the functions that build and take apart values of its type, so the tree can convert values to and from DynamicValue; the methods that need them take an implicit HasBinding[F]. In a Reflect.Unbound, where F is NoBinding, the nodes hold no functions; noBinding returns one.

A reflect is immutable: doc, modifier, defaultValue and the other setters return a copy. Two reflects are equal when their structure is equal; bindings, default values and examples are not compared. toString prints the tree in a schema definition language. A record, variant, sequence, map or wrapper node that appears more than once, as in a recursive type, is printed in full only the first time, and as deferred => and its type name after that; primitive and dynamic nodes are always printed in full.

case class Book(title: String, year: Int)
object Book {
 implicit val schema: Schema[Book] = Schema.derived
}

val reflect: Reflect.Bound[Book] = Book.schema.reflect
val kind       = reflect.nodeType                           // Record
val fieldNames = reflect.asRecord.map(_.fields.map(_.name)) // Some(Vector(title, year))
println(reflect)
// record Book {
//   title: String
//   year: Int
// }

Attributes

See also
Companion
object
Source
Reflect.scala
Supertypes
trait Reflectable[A]
class Object
trait Matchable
class Any
Known subtypes
class Deferred[F, A]
class Dynamic[F]
class Map[F, K, V, M]
class Primitive[F, A]
class Record[F, A]
class Sequence[F, A, C]
class Variant[F, A]
class Wrapper[F, A, B]
Show all
Self type
Reflect[F, A]
trait ReflectTransformer[-F[_, _], G[_, _]]

Rebuilds a Reflect tree with G in place of F at every node, through Reflect#transform. That method walks the tree and transforms the children of a node first; a transformer says how to rebuild each kind of node from its transformed children and the F it held. Reflect.Deferred nodes have no method of their own: Reflect.Deferred#transform handles them.

Rebuilds a Reflect tree with G in place of F at every node, through Reflect#transform. That method walks the tree and transforms the children of a node first; a transformer says how to rebuild each kind of node from its transformed children and the F it held. Reflect.Deferred nodes have no method of their own: Reflect.Deferred#transform handles them.

ReflectTransformer.noBinding strips the bindings of a reflect, DynamicSchema#rebind attaches them back, and type class derivation pairs each binding with a derived instance. Extend ReflectTransformer.OnlyMetadata when only the metadata changes.

Type parameters

F

what the nodes of the source reflect hold

G

what the nodes of the result hold

Attributes

See also
Companion
object
Source
ReflectTransformer.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class OnlyMetadata[F, G]
trait HasBinding[F]

The ReflectTransformer base class for metadata-only changes, and the transformer that strips bindings.

The ReflectTransformer base class for metadata-only changes, and the transformer that strips bindings.

Attributes

Companion
trait
Source
ReflectTransformer.scala
Supertypes
class Object
trait Matchable
class Any
Self type
trait Reflectable[A]

Something that carries documentation and modifiers: a Reflect node or a Term.

Something that carries documentation and modifiers: a Reflect node or a Term.

Attributes

Source
Reflectable.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
trait Reflect[F, A]
class Deferred[F, A]
class Dynamic[F]
class Map[F, K, V, M]
class Primitive[F, A]
class Record[F, A]
class Sequence[F, A, C]
class Variant[F, A]
class Wrapper[F, A, B]
class Term[F, S, A]
Show all

Derivation with derived, the built-in schemas of standard types (primitives, java.time types, UUID, Currency, options, collections, Either and DynamicValue), and fromJsonSchema.

Derivation with derived, the built-in schemas of standard types (primitives, java.time types, UUID, Currency, options, collections, Either and DynamicValue), and fromJsonSchema.

Attributes

Companion
class
Source
Schema.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Show all
Self type
Schema.type
final case class Schema[A](reflect: Bound[A]) extends SchemaVersionSpecific[A]

A Schema[A] describes the structure of the type A, such as the fields of a case class or the cases of a sealed trait, together with the functions that build and take apart values of A. Derive one with Schema.derived, then use it to get codecs for formats such as JSON, convert values to and from DynamicValue, compute and apply patches, and attach documentation, examples and default values.

A Schema[A] describes the structure of the type A, such as the fields of a case class or the cases of a sealed trait, together with the functions that build and take apart values of A. Derive one with Schema.derived, then use it to get codecs for formats such as JSON, convert values to and from DynamicValue, compute and apply patches, and attach documentation, examples and default values.

A schema is an immutable value: methods such as doc, defaultValue and modifier return a new schema. It wraps a Reflect.Bound[A], which holds the structure and its bindings.

case class Book(title: String, year: Int)
object Book {
 implicit val schema: Schema[Book] = Schema.derived
}

val json = Schema[Book].jsonCodec.encodeToString(Book("Zionomicon", 2021))
// {"title":"Zionomicon","year":2021}
val value = Schema[Book].toDynamicValue(Book("Zionomicon", 2021))
// {
//   title: "Zionomicon",
//   year: 2021
// }

Attributes

See also
Companion
object
Source
Schema.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
trait SchemaAspect[-Upper, +Lower, F[_, _]]

Represents a transformation or augmentation of a schema, applied to a specific range of types.

Represents a transformation or augmentation of a schema, applied to a specific range of types.

Type parameters

F

A type constructor representing the underlying structure for schema reflection.

Lower

The lower bound of types this SchemaAspect will guarantee compatibility with.

Upper

The upper bound of types this SchemaAspect can be applied to.

Attributes

Companion
object
Source
SchemaAspect.scala
Supertypes
class Object
trait Matchable
class Any
object SchemaAspect

The built-in aspects. Apply one with Schema#@@.

The built-in aspects. Apply one with Schema#@@.

Attributes

Companion
trait
Source
SchemaAspect.scala
Supertypes
class Object
trait Matchable
class Any
Self type

Adds derived to the Schema companion.

Adds derived to the Schema companion.

Attributes

Source
SchemaCompanionVersionSpecific.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object Schema
object SchemaError

Constructors of SchemaError values and the kinds of failure they hold.

Constructors of SchemaError values and the kinds of failure they hold.

The constructors that take a trace expect its path nodes from the innermost to the outermost, the order in which a decoder collects them. Pass Nil for the root, and add the path with atField and the other at* methods of the error.

Attributes

Companion
class
Source
SchemaError.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
final case class SchemaError(errors: ::[Single]) extends Exception, NoStackTrace

A SchemaError reports why decoding, conversion or validation failed. It holds one or more SchemaError.Single failures, each with the path (DynamicOptic) of the place in the data where it happened. Schema#fromDynamicValue collects the failures of all record fields in one error, while the JSON codec stops at the first failure.

A SchemaError reports why decoding, conversion or validation failed. It holds one or more SchemaError.Single failures, each with the path (DynamicOptic) of the place in the data where it happened. Schema#fromDynamicValue collects the failures of all record fields in one error, while the JSON codec stops at the first failure.

It extends Exception without a stack trace, so a Schema#transform function can throw it: the path of a failure says where it happened, not the stack.

val error = SchemaError.missingField(Nil, "title").atField("book") ++
 SchemaError.validationFailed("year must be positive").atField("year")

val text = error.message
// Missing field 'title' at: .book
// year must be positive at: .year

Attributes

See also
Companion
object
Source
SchemaError.scala
Supertypes
trait Product
trait Equals
trait NoStackTrace
class Exception
class Throwable
trait Serializable
class Object
trait Matchable
class Any
Show all
final case class SchemaExpr[A, B](dynamic: DynamicSchemaExpr, inputSchema: Schema[A], outputSchema: Schema[B])

A typed wrapper around DynamicSchemaExpr that provides compile-time type safety.

A typed wrapper around DynamicSchemaExpr that provides compile-time type safety.

Type parameters

A

The input type

B

The output type

Value parameters

dynamic

The underlying serializable expression

inputSchema

Schema for converting A to DynamicValue

outputSchema

Schema for converting DynamicValue back to B

Attributes

Companion
object
Source
SchemaExpr.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object SchemaExpr

Attributes

Companion
class
Source
SchemaExpr.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
SchemaExpr.type
object SchemaMatch

Provides matching logic for SchemaRepr patterns against DynamicValue instances.

Provides matching logic for SchemaRepr patterns against DynamicValue instances.

This object implements structural pattern matching between schema representations and runtime dynamic values, enabling the search optic to find values that match a given schema pattern.

==Matching Rules==

  • '''Wildcard''': Matches any DynamicValue
  • '''Primitive(name)''': Matches DynamicValue.Primitive where the underlying PrimitiveValue type matches the name (case-insensitive)
  • '''Record(fields)''': Matches DynamicValue.Record using subset matching - all specified fields must exist with matching types, but extra fields are allowed
  • '''Variant(cases)''': Matches DynamicValue.Variant if the case name matches one of the pattern cases and the payload matches that case's pattern
  • '''Sequence(elem)''': Matches DynamicValue.Sequence if all elements match the element pattern (empty sequence always matches)
  • '''Map(k, v)''': Matches DynamicValue.Map if all entries have matching key and value types (empty map always matches)
  • '''Optional(inner)''': Matches DynamicValue.Null always, otherwise checks inner pattern
  • '''Nominal(name)''': Returns false (requires schema context not available in DynamicValue)

Attributes

Source
SchemaMatch.scala
Supertypes
class Object
trait Matchable
class Any
Self type

Attributes

Companion
class
Source
SchemaMetadata.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
final case class SchemaMetadata[S, G[_]](map: Map[Optic[S, _], IndexedSeq[_]])

A schema metadata structure can store arbitrary metadata attached to the structure of a type.

A schema metadata structure can store arbitrary metadata attached to the structure of a type.

Attributes

Companion
object
Source
SchemaMetadata.scala
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
sealed trait SchemaRepr

A lightweight representation of schema structure for pattern matching in search optics.

A lightweight representation of schema structure for pattern matching in search optics.

SchemaRepr captures the shape of a type without runtime bindings, enabling structural matching against DynamicValue instances.

Attributes

Companion
object
Source
SchemaRepr.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class Map
class Nominal
class Optional
class Primitive
class Record
class Sequence
class Variant
object Wildcard
Show all
object SchemaRepr

Attributes

Companion
trait
Source
SchemaRepr.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
SchemaRepr.type

Adds structural to Schema.

Adds structural to Schema.

Attributes

Source
SchemaVersionSpecific.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class Schema[A]
Self type
Schema[A]

Constructors for search traversals, which the searchFor[T] step of CompanionOptics builds.

Constructors for search traversals, which the searchFor[T] step of CompanionOptics builds.

A search traversal converts the value to a DynamicValue. fold and check visit it depth first, left to right: the value itself, then record fields, case values, sequence elements, and both the keys and the values of maps. modify visits the same nodes except map keys, so a match that is a map key is read but never modified (see docs/dev/issues.md). Every node that decodes with the focus schema is a match, and the children of a match are searched too. modify applies f to each match and decodes the result with the source schema; if that decoding fails, it returns s unchanged. check reports an OpticCheck.EmptySequence when nothing matches.

Attributes

Source
Optic.scala
Supertypes
class Object
trait Matchable
class Any
Self type

Extension methods on values with a Schema, on JSON strings and on JSON bytes, available through import zio.blocks.schema._.

Extension methods on values with a Schema, on JSON strings and on JSON bytes, available through import zio.blocks.schema._.

Attributes

See also
Source
syntax.scala
Supertypes
class Object
trait Matchable
class Any
object Term

The kinds of term, and helpers for Term.

The kinds of term, and helpers for Term.

Attributes

Companion
class
Source
Term.scala
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
Term.type
final case class Term[F[_, _], S, A](name: String, value: Reflect[F, A], doc: Doc = ..., modifiers: Seq[Term] = ...) extends Reflectable[A]

A named child of a Reflect node: a field of a record or a case of a variant. S is the type of the record or variant, and A the type of the field or case; the type members Source and Focus name them.

A named child of a Reflect node: a field of a record or a case of a variant. S is the type of the record or variant, and A the type of the field or case; the type members Source and Focus name them.

Value parameters

doc

the documentation of the field or case

modifiers

modifiers such as Modifier.rename or Modifier.transient

name

the name of the field or case

value

the node of A

Attributes

Companion
object
Source
Term.scala
Supertypes
trait Serializable
trait Product
trait Equals
trait Reflectable[A]
class Object
trait Matchable
class Any
Show all
trait ToStructural[A]

Type class for converting nominal schemas to structural schemas.

Type class for converting nominal schemas to structural schemas.

Given a Schema[A] for a nominal type like a case class, this type class generates the corresponding structural type and provides a conversion method.

Example:

// scala-3-only
case class Person(name: String, age: Int)

val nominalSchema: Schema[Person] = Schema.derived[Person]
val structuralSchema: Schema[{ def name: String; def age: Int }] = nominalSchema.structural

In Scala 2 the compiler does not see the refined StructuralType, so nominalSchema.structural has type Schema[ts.StructuralType] and cannot be assigned to a Schema of the structural type.

Note: This is JVM-only due to reflection requirements for structural types.

Attributes

Companion
object
Source
ToStructural.scala
Supertypes
class Object
trait Matchable
class Any

Attributes

Companion
trait
Source
ToStructural.scala
Supertypes
class Object
trait Matchable
class Any
Self type

Attributes

Source
ToStructuralVersionSpecific.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object ToStructural
sealed trait Traversal[S, A] extends Optic[S, A]

A traversal focuses on zero or more parts of S at once: every element of a collection, the elements at some indices, every key or value of a map, the values at some keys, or every value of a type found anywhere in S (searchFor). Composing any optic with a traversal gives a traversal.

A traversal focuses on zero or more parts of S at once: every element of a collection, the elements at some indices, every key or value of a map, the values at some keys, or every value of a type found anywhere in S (searchFor). Composing any optic with a traversal gives a traversal.

fold and reduceOrFail read the parts, and modify updates all of them. When there are no parts, for example in an empty collection, fold returns its zero, modify returns a value equal to s, modifyOption returns None, and modifyOrFail and reduceOrFail return Left with an OpticCheck (OpticCheck.EmptySequence for an empty sequence).

case class Book(title: String, tags: List[String])
object Book extends CompanionOptics[Book] {
 implicit val schema: Schema[Book] = Schema.derived
 val tags: Traversal[Book, String] = $(_.tags.each)
}

val zionomicon = Book("Zionomicon", List("zio", "scala"))
Book.tags.fold[Int](zionomicon)(0, (count, _) => count + 1) // 2
Book.tags.modify(zionomicon, _.toUpperCase)                 // Book(Zionomicon,List(ZIO, SCALA))

Attributes

See also
Companion
object
Source
Optic.scala
Supertypes
trait Optic[S, A]
class Object
trait Matchable
class Any
Self type
Traversal[S, A]
object Traversal

Constructors for Traversal: compositions of two optics that give a traversal, and traversals over sequences and maps.

Constructors for Traversal: compositions of two optics that give a traversal, and traversals over sequences and maps.

Attributes

Companion
trait
Source
Optic.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Traversal.type

Hand-rolled Schema instances for all TypeId-related types.

Hand-rolled Schema instances for all TypeId-related types.

These schemas enable serialization/deserialization of TypeId metadata, which is essential for schema reflection and type-safe serialization.

Attributes

Source
TypeIdSchemas.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object DynamicSchema
object Schema
sealed trait Validation[+A]

A Validation is a declarative constraint on a primitive value, such as "positive" or "matches a pattern". It is stored in the PrimitiveType of a primitive schema.

A Validation is a declarative constraint on a primitive value, such as "positive" or "matches a pattern". It is stored in the PrimitiveType of a primitive schema.

Only DynamicSchema enforces it: check, conforms, and the decoding of the schema that toSchema returns. The JSON codec, Schema#fromDynamicValue and Schema#toJsonSchema ignore it, and Schema.derived never adds one. To reject values while decoding, check them in the to function of Schema#transform instead.

import zio.blocks.schema.binding.Binding

val pageCountType = PrimitiveType.Int(Validation.Numeric.Positive)
val pageCount: Schema[Int] =
 new Schema(new Reflect.Primitive[Binding, Int](pageCountType, pageCountType.typeId, Binding.Primitive.int))

val checked = pageCount.toDynamicSchema.check(DynamicValue.int(-5))
// Some(zio.blocks.schema.SchemaError: Validation failed: value must be positive)
val decoded = pageCount.fromDynamicValue(DynamicValue.int(-5)) // Right(-5)

Attributes

See also
Companion
object
Source
Validation.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object None
trait Numeric[A]
object Negative
object NonNegative
object NonPositive
object Positive
class Range[A]
class Set[A]
trait String
object Blank
object Empty
class Length
object NonBlank
object NonEmpty
class Pattern
Show all
object Validation

The built-in constraints.

The built-in constraints.

Attributes

Companion
trait
Source
Validation.scala
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Validation.type

Extensions

Inherited extensions

extension (inline sc: StringContext)
transparent inline def p(inline args: Any*): DynamicOptic

Parses a path literal into a DynamicOptic at compile time. The syntax is the one DynamicOptic#toString prints:

Parses a path literal into a DynamicOptic at compile time. The syntax is the one DynamicOptic#toString prints:

  • .name or name: a record field (a name starts with a letter or _ and goes on with letters, digits or _);
  • ``: a variant case;
  • [0], [0,2,5], [1:4] (indices 1, 2 and 3; empty when the end is not above the start), and [*], [:*] or [*:]: one index, several indices, a range of indices, or every element;
  • {"key"}, {'c'}, {42}, {-1}, {true} and {"a", "b"}: one map key, which is a string, char, Int or boolean literal, or several keys;
  • {*} or {:*}: every map value, and {*:}: every map key;
  • #Book, #string, #list(Book), #record { title: string }: a search for every value that matches a schema pattern (a SchemaRepr).

The empty literal p"" is the root path. Whitespace is allowed inside [], {} and &lt;, and inside a search pattern, but not between steps. String keys accept the escapes \", \\, \n, \t and \r, and char keys \', \\, \n, \t and \r. The macro reads the literal as written, without processing escapes first, so \" reaches the parser and is rejected: write string keys in a triple-quoted literal, p"""{"api.key"}""", or with the $" escape for a quote.

A malformed path is a compile error, and so is a literal with interpolated arguments. There is no syntax for a wrapper step, so p"..." rejects the .~ that DynamicOptic#toString prints for one (see docs/dev/issues.md).

val path: DynamicOptic = p".books[*].title"

path.nodes.toList                                                // List(Field(books), Elements, Field(title))
path == DynamicOptic.root.field("books").elements.field("title") // true

Attributes

See also
Inherited from:
PathInterpolator
Source
PathInterpolator.scala
extension [A](self: A)
def applyPatch(patch: Patch[A]): A

Applies patch to this value in lenient mode: operations that cannot be applied are skipped, and when the result does not convert back to A, this value is returned unchanged.

Applies patch to this value in lenient mode: operations that cannot be applied are skipped, and when the result does not convert back to A, this value is returned unchanged.

Attributes

Inherited from:
SyntaxVersionSpecific
Source
syntax.scala
def applyPatchStrict(patch: Patch[A]): Either[SchemaError, A]

Applies patch to this value in strict mode, returning Left when an operation of the patch cannot be applied.

Applies patch to this value in strict mode, returning Left when an operation of the patch cannot be applied.

Attributes

Inherited from:
SyntaxVersionSpecific
Source
syntax.scala
def diff(that: A)(using schema: Schema[A]): Patch[A]

Computes the patch that turns this value into that, as Schema#diff does.

Computes the patch that turns this value into that, as Schema#diff does.

Attributes

Inherited from:
SyntaxVersionSpecific
Source
syntax.scala
def show(using schema: Schema[A]): String

Renders this value as its DynamicValue, in the JSON-like EJSON text form with unquoted record keys.

Renders this value as its DynamicValue, in the JSON-like EJSON text form with unquoted record keys.

Attributes

Inherited from:
SyntaxVersionSpecific
Source
syntax.scala
def toJson(using schema: Schema[A]): Json

Encodes this value to a Json value with Schema#jsonCodec.

Encodes this value to a Json value with Schema#jsonCodec.

Attributes

Inherited from:
SyntaxVersionSpecific
Source
syntax.scala
def toJsonBytes(using schema: Schema[A]): Array[Byte]

Encodes this value to UTF-8 JSON bytes with Schema#jsonCodec.

Encodes this value to UTF-8 JSON bytes with Schema#jsonCodec.

Attributes

Inherited from:
SyntaxVersionSpecific
Source
syntax.scala
def toJsonString(using schema: Schema[A]): String

Encodes this value to a JSON string with Schema#jsonCodec, the codec derived with the default JSON deriver.

Encodes this value to a JSON string with Schema#jsonCodec, the codec derived with the default JSON deriver.

It ignores an implicit JsonCodec in scope and any deriver configured with withInstance or withModifier: to use such a deriver, derive the codec with Schema#derive and call encodeToString on it. An implicit Schema of a field type, by contrast, is used by Schema.derived.

case class Book(title: String, year: Int)
object Book {
 implicit val schema: Schema[Book] = Schema.derived
}

val json = Book("Zionomicon", 2021).toJsonString // {"title":"Zionomicon","year":2021}

Attributes

See also
Inherited from:
SyntaxVersionSpecific
Source
syntax.scala
extension (self: Array[Byte])
def fromJson[A](using schema: Schema[A]): Either[SchemaError, A]

Decodes a value of A from these UTF-8 JSON bytes with Schema#jsonCodec, returning Left with a SchemaError when the JSON is malformed or does not match the schema.

Decodes a value of A from these UTF-8 JSON bytes with Schema#jsonCodec, returning Left with a SchemaError when the JSON is malformed or does not match the schema.

Attributes

Inherited from:
SyntaxVersionSpecific
Source
syntax.scala