Into
Into[-A, +B] is a one-way conversion type class that converts values of type A into values of type B, returning Either[SchemaError, B] to represent both successful conversions and validation failures. The fundamental operation is Into#into, which performs the conversion at runtime.
Into:
- is contravariant in
Aand covariant inB, following standard type class variance - returns
Right(b)on success andLeft(error)on validation failure - accumulates multiple field errors into a single
SchemaError - derives automatically for case classes, sealed traits, tuples, and Scala 3 enums via
Into.derived
trait Into[-A, +B] {
def into(a: A): Either[SchemaError, B]
}
The variance and data flow can be visualised as:
A ──── into ────► Either[SchemaError, B]
│ │
│ Left(error) ← validation failure
│ Right(b) ← successful conversion
│
Contravariant in A, Covariant in B
Motivation
Into solves a common challenge in Scala applications: type-safe, validated conversion between structurally similar but different types. This arises in:
- Schema evolution: migrating data from an old API version to a new one
- Domain boundaries: converting between external DTOs and internal domain models
- Type refinement: promoting raw primitives into validated wrapper types
- Collection reshaping: converting between
List,Vector,Set,Array, etc.
Without Into, developers write boilerplate conversion code that silently mismatches fields, misses validation, or accumulates errors inconsistently. Into.derived generates all of this automatically at compile time.
import zio.blocks.schema.Into
case class PersonV1(name: String, age: Int)
case class PersonV2(name: String, age: Long, email: Option[String])
val migrate = Into.derived[PersonV1, PersonV2]
With migrate derived, converting a PersonV1 widens age to Long and defaults email to None:
migrate.into(PersonV1("Alice", 30))
// res0: Either[SchemaError, PersonV2] = Right(
// PersonV2(name = "Alice", age = 30L, email = None)
// )
Compare this to a manual implementation:
| Approach | Field mismatch detection | Error accumulation | Collection coercion |
|---|---|---|---|
| Manual conversion | ❌ Compile-time miss | ❌ Requires custom logic | ❌ Requires custom code |
Into.derived | ✅ Compile-time check | ✅ Automatic | ✅ Automatic |
Installation
Into is part of the zio-blocks-schema module:
// ZIO Blocks schema module
libraryDependencies += "dev.zio" %% "zio-blocks-schema" % "0.0.57"
For Scala.js:
// ZIO Blocks schema module
libraryDependencies += "dev.zio" %%% "zio-blocks-schema" % "0.0.57"
Supported Scala versions: 2.13.x and 3.x.
Creating Instances
There are four ways to obtain an Into[A, B] instance: summon a pre-existing implicit, derive one at compile time via macro, use the built-in identity instance, or implement the trait directly for custom logic.
Into.apply — Summoning
Summons an implicit Into[A, B] instance from the implicit scope. This is the standard way to access a pre-existing instance:
object Into {
def apply[A, B](implicit ev: Into[A, B]): Into[A, B]
}
We summon the pre-existing Into[Int, Long] widening instance and call Into#into on it:
import zio.blocks.schema.Into
val intToLong: Into[Int, Long] = Into[Int, Long]
With intToLong in scope, Into#into converts the value and returns a Right:
intToLong.into(42)
// res1: Either[SchemaError, Long] = Right(42L)
Into.derived — Macro Derivation
Generates an Into[A, B] instance at compile time using a macro. This is the primary way to convert between case classes, sealed traits, tuples, and enums:
object Into {
def derived[A, B]: Into[A, B] // macro
}
We derive the conversion between two case classes and observe the count field being widened from Int to Long:
import zio.blocks.schema.Into
case class Source(name: String, count: Int)
case class Target(name: String, count: Long)
val conv = Into.derived[Source, Target]
The derived conv maps each field by name, coercing types where needed:
conv.into(Source("events", 100))
// res2: Either[SchemaError, Target] = Right(
// Target(name = "events", count = 100L)
// )
Into.identity — Identity Conversion
A pre-provided implicit Into[A, A] that always succeeds. It is always in scope and is resolved automatically when source and target types are the same:
object Into {
implicit def identity[A]: Into[A, A]
}
Any Into[A, A] resolves to this built-in — there is nothing to configure:
import zio.blocks.schema.Into
val same: Into[String, String] = Into[String, String]
The identity conversion always returns Right wrapping the original value:
same.into("hello")
// res3: Either[SchemaError, String] = Right("hello")
Custom Instances
We can implement Into manually for any types that need custom conversion logic:
import zio.blocks.schema.Into
case class Celsius(value: Double)
case class Fahrenheit(value: Double)
implicit val celsiusToFahrenheit: Into[Celsius, Fahrenheit] =
(c: Celsius) => Right(Fahrenheit(c.value * 9.0 / 5.0 + 32.0))
With celsiusToFahrenheit in implicit scope, Into[Celsius, Fahrenheit] resolves to it automatically:
Into[Celsius, Fahrenheit].into(Celsius(100.0))
// res4: Either[SchemaError, Fahrenheit] = Right(Fahrenheit(212.0))
Predefined Instances
ZIO Blocks ships built-in Into instances for all standard numeric types and common container types. These are resolved automatically from implicit scope — no import or explicit call is needed.
Numeric Widening
These instances always succeed. Most cannot lose information, but Int to Float, Long to Float and Long to Double round a value with more significant digits than the target holds: Into[Int, Float].into(16777217) gives Right(1.6777216E7).
| From \ To | Short | Int | Long | Float | Double |
|---|---|---|---|---|---|
Byte | ✅ | ✅ | ✅ | ✅ | ✅ |
Short | ✅ | ✅ | ✅ | ✅ | |
Int | ✅ | ✅ | ✅ | ||
Long | ✅ | ✅ | |||
Float | ✅ |
Each widening conversion always returns Right:
Into[Byte, Int].into(42.toByte)
// res5: Either[SchemaError, Int] = Right(42)
Into[Int, Long].into(100)
// res6: Either[SchemaError, Long] = Right(100L)
Into[Float, Double].into(3.14f)
// res7: Either[SchemaError, Double] = Right(3.140000104904175)
Numeric Narrowing (With Validation)
These instances check at runtime whether the value fits in the target type. They return Left(SchemaError) when the value is out of range or cannot be precisely represented:
| From | To | Fails when |
|---|---|---|
Short | Byte | value outside [-128, 127] |
Int | Byte | value outside [-128, 127] |
Int | Short | value outside [-32768, 32767] |
Long | Byte | value outside [-128, 127] |
Long | Short | value outside [-32768, 32767] |
Long | Int | value outside [Int.MinValue, Int.MaxValue] |
Double | Float | value outside Float range |
Float | Int | value is not a whole number, or outside Int range |
Float | Long | value is not a whole number, or outside Long range |
Double | Int | value is not a whole number, or outside Int range |
Double | Long | value is not a whole number, or outside Long range |
A value within range returns Right; an overflow or fractional value returns Left:
Into[Long, Int].into(42L)
// res8: Either[SchemaError, Int] = Right(42)
Into[Long, Int].into(Long.MaxValue)
// res9: Either[SchemaError, Int] = Left(
// SchemaError(
// List(
// ConversionFailed(
// source = DynamicOptic(ArraySeq()),
// details = "Value 9223372036854775807 is out of range for Int [-2147483648, 2147483647]",
// cause = None
// )
// )
// )
// )
Into[Double, Int].into(3.14)
// res10: Either[SchemaError, Int] = Left(
// SchemaError(
// List(
// ConversionFailed(
// source = DynamicOptic(ArraySeq()),
// details = "Value 3.14 cannot be precisely converted to Int",
// cause = None
// )
// )
// )
// )
Container Instances
Into composes through standard container types automatically:
Option
optionInto lifts an Into[A, B] to work over Option, coercing the element when present and passing None through unchanged:
implicit def optionInto[A, B](implicit into: Into[A, B]): Into[Option[A], Option[B]]
Both Some and None are handled:
Into[Option[Int], Option[Long]].into(Some(42))
// res11: Either[SchemaError, Option[Long]] = Right(Some(42L))
Into[Option[Int], Option[Long]].into(None)
// res12: Either[SchemaError, Option[Long]] = Right(None)
Either
eitherInto coerces both branches independently, requiring separate Into instances for the left and right types:
implicit def eitherInto[L1, R1, L2, R2](
implicit leftInto: Into[L1, L2],
rightInto: Into[R1, R2]
): Into[Either[L1, R1], Either[L2, R2]]
Both Left and Right branches are coerced independently:
Into[Either[Int, Int], Either[Long, Long]].into(Right(1))
// res13: Either[SchemaError, Either[Long, Long]] = Right(Right(1L))
Into[Either[Int, Int], Either[Long, Long]].into(Left(2))
// res14: Either[SchemaError, Either[Long, Long]] = Right(Left(2L))
Map
mapInto coerces both keys and values, requiring separate Into instances for each:
implicit def mapInto[K1, V1, K2, V2](
implicit keyInto: Into[K1, K2],
valueInto: Into[V1, V2]
): Into[Map[K1, V1], Map[K2, V2]]
Both keys and values are coerced element-by-element:
Into[Map[String, Int], Map[String, Long]].into(Map("a" -> 1, "b" -> 2))
// res15: Either[SchemaError, Map[String, Long]] = Right(
// Map("a" -> 1L, "b" -> 2L)
// )