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-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.Function1.cons;
import static com.github.tonivade.purefun.Function1.fail;
import static com.github.tonivade.purefun.Matcher1.never;
import static com.github.tonivade.purefun.Precondition.checkNonNull;

public final class Pattern1 implements PartialFunction1 {

  private final PartialFunction1 function;

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

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

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

  @SuppressWarnings("unchecked")
  public  ThenStep, T, R> when(Class type) {
    return handler -> add(Matcher1.instanceOf(type), value -> handler.apply((T) value));
  }

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

  @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)));
  }
  
  @FunctionalInterface
  public interface ThenStep {

    P then(Function1 handler);
    
    default P returns(R value) {
      return then(cons(value));
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy