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

com.github.tonivade.purefun.Pattern1 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;

import static com.github.tonivade.purefun.Function1.cons;
import static com.github.tonivade.purefun.Function1.fail;
import static com.github.tonivade.purefun.Matcher1.invalid;
import static com.github.tonivade.purefun.Matcher1.never;
import static java.util.Objects.requireNonNull;

public final class Pattern1 implements PartialFunction1 {

  private final PartialFunction1 function;

  private Pattern1(PartialFunction1 function) {
    this.function = requireNonNull(function);
  }

  public static  Pattern1 build() {
    return new Pattern1<>(PartialFunction1.of(never(), fail()));
  }

  public CaseBuilder1, A, R> when(Matcher1 matcher) {
    return new CaseBuilder1<>(this::add).when(matcher);
  }

  public CaseBuilder1, A, R> otherwise() {
    return new CaseBuilder1<>(this::add).when(Matcher1.otherwise());
  }

  @Override
  public R apply(A value) {
    return function.apply(value);
  }

  @Override
  public boolean isDefinedAt(A value) {
    return function.isDefinedAt(value);
  }

  protected Pattern1 add(Matcher1 matcher, Function1 handler) {
    return new Pattern1<>(function.orElse(PartialFunction1.of(matcher, handler)));
  }

  public static final class CaseBuilder1 {

    private final Function2, Function1, B> finisher;
    private final Matcher1 matcher;

    private CaseBuilder1(Function2, Function1, B> finisher) {
      this.finisher = requireNonNull(finisher);
      this.matcher = invalid();
    }

    private CaseBuilder1(Function2, Function1, B> finisher, Matcher1 matcher) {
      this.finisher = requireNonNull(finisher);
      this.matcher = requireNonNull(matcher);
    }

    public CaseBuilder1 when(Matcher1 matcher) {
      return new CaseBuilder1<>(finisher, matcher);
    }

    public B then(Function1 handler) {
      return finisher.apply(matcher, handler);
    }

    // XXX: I have to rename this method because eclipse complains, it says that there are ambiguous.
    // javac compiler works fine.
    // related bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=522380
    public B returns(R value) {
      return then(cons(value));
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy