Data type of Function with void return type and taking no input parameters

98 Views Asked by At

I am unable to figure what would be the return type of these functions fooBar() and barFoo() in Java and getting the following errors.

import java.util.function.Function;

class FooBar {
  private void foo() {
  }

  private void bar(String s) {
  }

  public FunctionalInterface fooBar() {
    return this::foo;// The type of foo() from the type FooBar is void, this is incompatible with the
                     // descriptor's return type: Class<? extends Annotation>
  }

  public Function<String, Void> barfoo() {
    return this::bar;// The type of bar(String) from the type FooBar is void, this is incompatible
                     // with the descriptor's return type: Void
  }
}

Is there any way to return these functions, so that they can be used by other functions?

Setting return type to FuncionalInterface isn't helpful. Setting return type to Void, but however it isn't compatible with void

Thanks!

2

There are 2 best solutions below

0
tgdavies On BEST ANSWER

There are types which match void f() and void f(String a). They are Runnable and Consumer<String> respectively.

So your code becomes:

import java.util.function.Consumer;

class FooBar {
    private void foo() {
    }

    private void bar(String s) {
    }

    public Runnable fooBar() {
        return this::foo;
    }

    public Consumer<String> barfoo() {
        return this::bar;
    }
}
0
Elliott Frisch On

A Function has a <T,R> generic type, you are looking for Runnable (a void, void function) and Consumer<T> (a void, T function). Like,

public Runnable fooBar() {
    return this::foo;
}

public Consumer<String> bar() {
    return this::bar;
}