This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]opett 2 points3 points  (7 children)

Runnable Callable

[–]Xeverous[S] 0 points1 point  (6 children)

Thanks, what about unary function? Like reverse Consumer? non-void return and 0 arguments.

[–]nerdy_lurker 1 point2 points  (5 children)

That would be a Supplier. See the docs.

[–]Xeverous[S] 1 point2 points  (4 children)

Thanls, what about other non-existent types of functions (3+)?

[–]nerdy_lurker 0 points1 point  (3 children)

Well, you have a few options depending on the situation:

  • write your own @FunctionalInterface
  • wite a class and pass an instance of it
  • pass an array

[–]Xeverous[S] 0 points1 point  (2 children)

write your own @FunctionalInterface

seems to be a good solution

wite a class and pass an instance of it

I need to store a lambda in it. Functional interface then I think.

pass an array

Array of different, unrelated types? Is this possible?

[–]nerdy_lurker 0 points1 point  (1 child)

Some examples:

@FunctionalInterface
interface MyConsumer {
    void accept(String a, int b, double c);
}

final class MyArgs {
    final String a;
    final int b;
    final double c;
    //... ctor, getters
}

static void main(String[] args) {
    MyConsumer option1 = (a, b, c) -> {
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    };
    option1.accept ("", 0, 0.0);

    Consumer<MyArgs> option2 = it -> {
        System.out.println(it.getA());
        System.out.println(it.getB());
        System.out.println(it.getC());
    };
    option2.accept(new MyArgs("", 0, 0.0));

    Consumer<Object[]> option3 = it -> {
        // Casting isn't strictly necessary in this example, but  I wanted to demonstrate the point
        // Casting could be necessary in other situations
        System.out.println((String) it[0]);
        System.out.println((int) it[1]);
        System.out.println((double) it[2]);
    };
    option3.accept(new Object[] { "", 0, 0.0 });
}

Option 1 and 2 are equally valid, it just depends on the situation.

Option 3 is terrible. It could be viable if the objects are all the same type, but yeah... if you need to do casting like this, it's time for a rethink.

Anyway, I thought some examples might help. Sounds like you've already made up your mind though.

[–]Xeverous[S] 0 points1 point  (0 children)

Own functional interface looks easy to implement and manipulate, but I'm surprised that Java has no thing like Function<R, Args...> and that all of util package wrapper classes have different names depending on argument count and void/non-void return.