Skip to content

bvkatwijk/java-lens

Repository files navigation

java-lens

Automatic lens generation to support transformations to records.

Maven Central Version ci codecov

Purpose

If you use records and you want to apply some transformation, code can get verbose, repetitive and error-prone. For example:

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) { }

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(ALICE);
}

Usage

Add @Lenses annotation to your record(s)

@Lenses
public record Person(String name, Address address, Address work, List<Person> friends) { }

See Examples for more usage examples.

Development

Annotation Debugging

Run gradle compiler in debug mode

./gradlew --no-daemon -Dorg.gradle.debug=true clean build

Gradle process will wait for debugger to attach. Run IDE debugging process for port 5005.