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 PLens delegate;

  protected Lens(PLens delegate) {
    this.delegate = requireNonNull(delegate);
  }

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

  public A get(S target) {
    return delegate.get(target);
  }

  public S set(S target, A value) {
    return delegate.set(target, value);
  }

  public Function1 set(S target) {
    return delegate.set(target);
  }

  public Operator1 modify(Operator1 mapper) {
    return delegate.modify(mapper)::apply;
  }

  public Operator1 modify(A newValue) {
    return delegate.modify(newValue)::apply;
  }

  public Optional asOptional() {
    return new Optional<>(delegate.asOptional());
  }

  public  Lens compose(Lens other) {
    return new Lens<>(delegate.compose(other.delegate));
  }

  public  Optional compose(Optional other) {
    return asOptional().compose(other);
  }

  public  Lens compose(Iso other) {
    return compose(other.asLens());
  }

  public  Optional compose(Prism other) {
    return asOptional().compose(other.asOptional());
  }
}