All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.tonivade.purefun.optics.Lens Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2019, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.optics;

import static java.util.Objects.requireNonNull;

import com.github.tonivade.purefun.Function1;
import com.github.tonivade.purefun.Function2;
import com.github.tonivade.purefun.Operator1;

public final class Lens {

  private final Function1 getter;
  private final Function2 setter;

  private Lens(Function1 getter, Function2 setter) {
    this.getter = requireNonNull(getter);
    this.setter = requireNonNull(setter);
  }

  public static  Lens of(Function1 getter, Function2 setter) {
    return new Lens<>(getter, setter);
  }

  public R get(T target) {
    return getter.apply(target);
  }

  public T set(T target, R value) {
    return set(target).apply(value);
  }

  public Function1 set(T target) {
    return setter.curried().apply(target);
  }

  public Operator1 modify(Operator1 mapper) {
    return target -> set(target).apply(mapper.apply(getter.apply(target)));
  }

  public Operator1 modify(R newValue) {
    return modify(ignore -> newValue);
  }

  public  Lens compose(Lens other) {
    return new Lens<>(
        target -> other.get(this.get(target)),
        (target, value) -> this.set(target).apply(other.modify(value).apply(this.get(target))));
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy