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

com.github.tonivade.purefun.Pattern2 Maven / Gradle / Ivy

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

import static com.github.tonivade.purefun.Function2.cons;
import static com.github.tonivade.purefun.Precondition.checkNonNull;

public class Pattern2 implements PartialFunction2 {

  private final Pattern1, R> pattern;

  private Pattern2() {
    this(Pattern1.build());
  }

  private Pattern2(Pattern1, R> pattern) {
    this.pattern = checkNonNull(pattern);
  }

  @Override
  public boolean isDefinedAt(A a, B b) {
    return pattern.isDefinedAt(Tuple.of(a, b));
  }

  @Override
  public R apply(A a, B b) {
    return pattern.apply(Tuple.of(a, b));
  }

  public static  Pattern2 build() {
    return new Pattern2<>();
  }

  public ThenStep, A, B, R> when(Matcher2 matcher) {
    return handler -> add(matcher, handler);
  }

  public ThenStep, A, B, R> otherwise() {
    return handler -> add(Matcher2.otherwise(), handler);
  }

  private Pattern2 add(Matcher2 matcher, Function2 handler) {
    return new Pattern2<>(pattern.add(matcher.tupled(), handler.tupled()));
  }
  
  @FunctionalInterface
  public interface ThenStep {
    
    P then(Function2 handler);
    
    default P returns(R value) {
      return then(cons(value));
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy