Preface
This question is specifically targeting Java
answers. I have little to no knowledge of any other program languages, though I expect that the questions I raise below will apply to other statically-typed languages as well. This question was "inspired" by this PPCG answer.
Java Lambdas
(skip this if you know Java and how Java lambda's work)
So, in statically typed languages, everything has a type at compile-time - including lambdas. In Java lambdas are all instances of some interface
which is considered a FunctionalInterface
. An interface
is functional iff it contains only 1 non-default
method. Lambdas for that interface
can then be created implementing that 1 method. For example, below is the (simplified) source code for Java's Function
class:
public interface Function<T, R> {
R apply(T t);
}
Lambdas of the type Function<T, R>
can then be implemented like: t -> r
, where t
is the input and r
is the return value. Function
is just one of the many functional interfaces Java provides, others include Predicate
, Consumer
, Supplier
, BiFunction
, etc. In addition, interfaces which already existed but, as of Java 8, fit the definition of functional interfaces (such as Runnable
) can also be implemented as lambdas.
The Question
Every answer posted as a Java lambda that I've seen (up until the one that inspired this question) uses one of the default Java types. I myself always specify what type the lambda is, to avoid any confusion. The question I have now is, can one just arbitrarily write a lambda, with as many parameters required, and submit it, as is done in this answer (and claim it implements a custom functional interface)?
Can lambdas be submitted as answers despite requiring an additional class declaration?
Notes
- I do not intend to specifically call out Okx's answer; it just so happens to be the one that spurred me to write this question. As far as I can tell, no community consensus was reached on this issue before they posted it, so don't go flooding their answer with down votes...
- Of course, you could also just use a certain lambda library I may or may not have created and side step this whole issue... and Java isn't going to win any code-golf challenges anyway... this kind of feels like a pointless question now... Anyway, thoughts?
- If this question is a duplicate, I apologize, I couldn't find any other similar questions with the search term:
lambda AND class is:question