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
    };
}
3
  • I would get your examples to compile first. Why are you ignoring t in getFunctions? Commented May 2, 2016 at 10:19
  • @Tunaki I want to return an array of Functions like I showcased in the first code block. Commented May 2, 2016 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<Function<Boolean, Integer>> instead. Commented May 2, 2016 at 10:36

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.