What would be the best practice to declare lambdas in Java8 code? How it was designed to be used?
For example, let's say that we have a method that accept a Function
. I want to provide function implementation that can be reusable. So I can do this:
[A] Implement a Function
interface:
public class Foo implements Function<A,B> {
public B apply(A a) {...}
}
...
useFunction(new Foo());
[B] Declare Function
as lambda in some static
field:
public interface Foo {
Function<A,B> bar = it -> { ....}
}
...
useFunction(Foo.bar);
[C] Use method reference:
public class Foo {
public static B bar(A a) {...}
}
...
useFunction(Foo::bar);
Until functional programing in java8, I tried not to pollute code with static
s. However, now I am somehow 'forced' to use statics (or global singletons) for storing reusable lambdas.
Aucun commentaire:
Enregistrer un commentaire