Constructor
A Constructor builds a value of type A from Registers: it is the construction half of a Binding.Record. To decode a record, a codec writes each field into registers, at the positions that Reflect.Record#registers gives, and then calls construct. Reading the fields from registers, instead of from a tuple or an array of boxed values, keeps primitive fields unboxed.
construct reads at positions counted from its offset argument. A record decoded on its own starts at RegisterOffset.Zero; the JSON codec keeps one Registers as a stack and passes the start of the record's part of it. A RegisterOffset counts the registers before a field, so year below, which comes after one object field, is at RegisterOffset(objects = 1), whose byte position is 0:
import zio.blocks.schema.binding._
import zio.blocks.schema.binding.RegisterOffset.RegisterOffset
case class Book(title: String, year: Int)
val bookConstructor: Constructor[Book] = new Constructor[Book] {
def usedRegisters: RegisterOffset = RegisterOffset(objects = 1, ints = 1)
def construct(in: Registers, offset: RegisterOffset): Book =
Book(in.getObject(offset).asInstanceOf[String], in.getInt(offset + RegisterOffset(objects = 1)))
}
val registers = Registers(bookConstructor.usedRegisters)
registers.setObject(RegisterOffset.Zero, "Zionomicon")
registers.setInt(RegisterOffset(objects = 1), 2021)
val book = bookConstructor.construct(registers, RegisterOffset.Zero) // Book("Zionomicon", 2021)
Type parameters
- A
-
the type of the values it builds
Attributes
- See also
- Source
- Constructor.scala
- Graph
-
- Supertypes
- Known subtypes
-
class ConstantConstructor[A]
- Self type
-
Constructor[A]