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

com.github.tonivade.purefun.CheckedProducer 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 com.github.tonivade.purefun.type.Either;
import com.github.tonivade.purefun.type.Option;
import com.github.tonivade.purefun.type.Try;

@FunctionalInterface
public interface CheckedProducer extends Recoverable {

  A get() throws Throwable;

  default  CheckedFunction1 asFunction() {
    return value -> get();
  }

  default Producer> liftTry() {
    return () -> Try.of(this);
  }

  default Producer> liftOption() {
    return liftTry().andThen(Try::toOption);
  }

  default Producer> liftEither() {
    return liftTry().andThen(Try::toEither);
  }

  default  CheckedProducer andThen(CheckedFunction1 after) {
    return () -> after.apply(get());
  }

  default Producer recover(Function1 mapper) {
    return () -> {
      try {
        return get();
      } catch (Throwable e) {
        return mapper.apply(e);
      }
    };
  }

  default Producer unchecked() {
    return recover(this::sneakyThrow);
  }

  static  CheckedProducer unit(A value) {
    return () -> value;
  }

  static  CheckedProducer failure(Producer supplier) {
    return () -> { throw supplier.get(); };
  }

  static  CheckedProducer of(CheckedProducer reference) {
    return reference;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy