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

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

/*
 * Copyright (c) 2018-2020, 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;

/**
 * This interface represents a function without any parameter. Similar to {@link java.util.function.Supplier}
 * but with additional functionality like the ability to memoize the result.
 * @param  the returned type
 */
@HigherKind
@FunctionalInterface
public interface Producer extends Recoverable {

  default T get() {
    try {
      return run();
    } catch (Throwable t) {
      return sneakyThrow(t);
    }
  }

  T run() throws Throwable;

  default  Function1 asFunction() {
    return value -> run();
  }

  default  Producer map(Function1 after) {
    return () -> after.apply(get());
  }

  default  Producer flatMap(Function1> after) {
    return () -> after.apply(get()).get();
  }

  default Producer> liftOption() {
    return map(Option::of);
  }

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

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

  default Producer memoized() {
    return new MemoizedProducer<>(this);
  }

  static  Producer cons(T value) {
    return () -> value;
  }

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

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




© 2015 - 2025 Weber Informatics LLC | Privacy Policy