Search code examples
javafunctional-programming

How to create mapper function for a thunk in Java


I cant get this map method right. I need to specify the generic Think<R> but where?

public class Think<T> implements Supplier<T> {

  private Supplier<T> supplier;

  public Think(Supplier<T> expression) {
    this.supplier = () -> evaluate(expression);
  }

  public static <T> Think<T> of(T value) {
    return new Think<>(() -> value);
  }

  private synchronized T evaluate(Supplier<T> expression) {
    this.supplier = expression;
    return this.supplier.get();
  }

  @Override
  public T get() {
    return this.supplier.get();
  }

  public <R> Think<R> map(Function<? super T, ? extends R> mapper) {
    return Think.of(() -> mapper.apply(get()));
  }

yields

incompatible types: cannot infer type-variable(s) T (argument mismatch; R is not a functional interface)


Solution

  • The method map itself is correct, but the problem arises when you call Think.of().

    Change Think.of() method to accept a Supplier instead of a direct value of type R.

    public static <T> Think<T> of(Supplier<T> supplier) {
        return new Think<>(supplier);
    }