Automatic lens generation to support transformations to records.
If you use records and you want to apply some transformation, code can get verbose, repetitive and error-prone. Say we have a layered immutable structure:
public record Person(String name, Address address, Address work, List<Person> friends) { }
public record Address(String street, int number, City city) { }
public record City(String name) { }Without lenses the verbosity scales with both the amount of fields and layers. For example:
public static Person moveToNewYork(Person person) {
Address address = person.address;
var updatedCity = new City("New York");
var updatedAddress = new Address(address.street, address.number, updatedCity);
return new Person(person.name, updatedAddress, person.work, person.friends);
}Using Lenses you can annotate your records, giving you a DSL to make specific changes:
public static Person moveToNewYork(Person person) {
return PersonLens.µ
.address()
.city()
.name()
.with("New York")
.apply(person);
}Each part of the DSL is an immutable functional object allowing easy extraction and reuse, for example:
public static final Lens<Person, String> PERSON_CITY_NAME_LENS = PersonLens.µ
.address()
.city()
.name()
public static final Function<Person, Person> PERSON_MOVE_NEW_YORK = PERSON_CITY_NAME_LENS.with("New York")Add @Lenses annotation to your record(s)
@Lenses
public record Person(String name, Address address, Address work, List<Person> friends) { }See ExampleTest for more usage examples.
The library has a runtime dependency on Vavr.
Run gradle compiler in debug mode
./gradlew --no-daemon -Dorg.gradle.debug=true clean buildGradle process will wait for debugger to attach. Run IDE debugging process for port 5005.