diff --git a/chimney/src/main/scala-3/io/scalaland/chimney/dsl/TransformerInto.scala b/chimney/src/main/scala-3/io/scalaland/chimney/dsl/TransformerInto.scala index 57a11390f..347961b5b 100644 --- a/chimney/src/main/scala-3/io/scalaland/chimney/dsl/TransformerInto.scala +++ b/chimney/src/main/scala-3/io/scalaland/chimney/dsl/TransformerInto.scala @@ -211,6 +211,13 @@ final class TransformerInto[From, To, Overrides <: TransformerOverrides, Flags < )(using IsFunction.Of[Ctor, To]): TransformerInto[From, To, ? <: TransformerOverrides, Flags] = ${ TransformerIntoMacros.withConstructorImpl('this, 'f) } + /** Require that all fields of the source object except fields mentioned in `selectorFrom` are used in the + * transformation. and fail compilation otherwise. + * + * @param selectorFrom + * exception fields that are not required to be used in the transformation + * @return + */ transparent inline def requireSourceFieldsUsedExcept( inline selectorFrom: From => Any* ): TransformerInto[From, To, ? <: TransformerOverrides, Flags] = diff --git a/docs/docs/supported-transformations.md b/docs/docs/supported-transformations.md index 74318232a..f2c40fe11 100644 --- a/docs/docs/supported-transformations.md +++ b/docs/docs/supported-transformations.md @@ -759,6 +759,41 @@ If the flag was enabled in the implicit config it can be disabled with `.disable // Consult https://chimney.readthedocs.io for usage examples. ``` +### Require source fields to be used + +If you want to enforce that every field of the source type is used in the transformation, you can enable the +`.requireSourceFieldsUsedExcept` setting. This setting also allows you to add fields you'd like to ignore: + +!!! example + + ```scala + //> using dep io.scalaland::chimney::{{ chimney_version() }} + import io.scalaland.chimney.dsl._ + + case class Source(a: String, b: Int, c: String) + case class Target(a: String) + + Source("value", 512, "anotherValue") + .into[Target] + .requireSourceFieldsUsedExcept() + .transform + // Chimney can't derive transformation from Source to Target + // + // Target + // field(s) b, c of Source are required to be used in the transformation but are not used! + // + // Consult https://chimney.readthedocs.io for usage examples. + + pprint.pprintln( + Source("value", 512, "anotherValue") + .into[Target] + .requireSourceFieldsUsedExcept(_.b, _.c) + .transform + ) + // expected output: + // Target(a = "value") + ``` + ### Writing to Bean setters If we want to write to `def setFieldName(fieldName: A): Unit` as if it was `fieldName: A` argument of a constructor -