java - How do I stop a functional interface from being a target for lambda expressions? -
i have api interface 2 (overloaded) methods of same name take different argument types. these different types both technically functional interfaces, user should not allowed create instances of 1 of them. here simplified example:
public class example { @functionalinterface public interface computation { int compute(); } public interface wrappedcomputation { computation unwrap(); } public static class solver { public static int solve(computation a) { return a.compute(); } public static int solve(wrappedcomputation b) { return solve(b.unwrap()); } } public static void main(string... args) { // 'computation' interface should lambda target // coder can make own 'a' computation solver.solve( () -> { return 5 + 5; } ); // 'wrappedcomputation' interface should not lambda target // or else coder can cause runtime exceptions etc., passing null 'computation' reference computed solver.solve( () -> { computation = null; return a; } ); } }
the idea have far add dummy/unused method interface don't want lambda target, , implement in of implementing classes. seems little sloppy/unneeded though... other suggestions?
there no way prevent usage of lambda expressions api clients when interface satisfies the criteria it.
your supposition api clients can only cause trouble via lambdas incorrect -- bad thing can lambda, can anonymous inner class or named class. consider:
solver.solve( new wrappedcomputation(){ public computation unwrap(){ computation = null; return a; } });
this has same semantics , end result (a runtime exception) lambda.
perhaps want instead prevent any uncontrolled creation of wrappedcomputation
? in case, consider making final class
constructor checks error cases:
public final class wrappedcomputation{ private final computation _wrapped; public wrappedcomputation(@nonnull wrapped){ _wrapped = objects.requirenonnull(wrapped); } }
Comments
Post a Comment