3

I have an array of methods which can be called and need a boolean as a parameter. I have tried this:

public class Example {
    public Function<Boolean, Integer> getFunctions(boolean t) {
        return new Function[] {
            this::magicNumber
        };
    }

    public int magicNumber(boolean t) {
        return (t) ? new Random().nextInt(11) : 0;
    }
}

But then the compiler returns an error message with the message

Incompatible types: invalid method reference
    Incompatible types: Object cannot be converted to boolean

The example above however can work by storing the Function in a variable and returning that, however I don't find this clean code and it's redundant.

public class Example {
    public Function<Boolean, Integer> getFunctions(boolean t) {
        Function<Boolean, Integer> f = this::magicNumber;

        return new Function[] {
            f
        };
    }

    public int magicNumber(boolean t) {
        return (t) ? new Random().nextInt(11) : 0;
    }
}

Is there any way to shorten the code above like in the example in the beginning?

EDIT

As a commenter requested, I will give a short example of how I used Supplier in a previous project. I return them in an array to return objects. The problem is that this project depends on having a parameter.

public Supplier<T>[] getRecipes()
{
    return new Supplier[] {
        this::anchovyRule,
        this::codRule,
        this::herringRule,
        this::lobsterRule,
        this::mackerelRule,
        this::pikeRule,
        this::salmonRule,
        this::sardineRule,
        this::shrimpRule,
        this::troutRule,
        this::tunaRule
    };
}
DevNebulae
  • 4,566
  • 3
  • 16
  • 27
  • I would get your examples to compile first. Why are you ignoring `t` in `getFunctions`? – Peter Lawrey May 02 '16 at 10:19
  • @Tunaki I want to return an array of Functions like I showcased in the first code block. – DevNebulae May 02 '16 at 10:26
  • 1
    @GamerNebulae as Tunaki shows, arrays and generics do not mix very well. Unless there is a specific reason why it needs to be an array, use a collection such as a `List>` instead. – Jesper May 02 '16 at 10:36

1 Answers1

3

How about return List<Function<Boolean, Integer>> like this.

public class Example {
    public List<Function<Boolean, Integer>> getFunctions(boolean t) {
        return Arrays.asList(
            this::magicNumber
        );
    }

    public int magicNumber(boolean t) {
        return (t) ? new Random().nextInt(11) : 0;
    }
}