When a contract end nears it’s time to start interviewing again, and time to realise what we don’t know or what we do know, but can’t articulately explain. This leads me to my first Things I Should Know But Somehow Don’t (TISKBSD) post.
I know what a Lambda is, I use them nearly every day when coding, but when asked the question I found I myself babbling far too much for my liking, so here I try to rectify that.
Writing it down should allow me to cement things in my mind and also cover any gaps in my knowledge. I am not trying to break new ground with these posts, but simply collect topics in a suitable place largely for my own benefit and on the off-chance that others also find it useful.
What is a Lambda (in Java)?
A Lambda Expression in Java is simply a compact way to create/represent single-method classes, i.e., classes that implement a Functional Interface. More generally a Lambda is an anonymous function.
Performance: For most developers, Lambda Expressions, are syntactic sugar, allowing them to write more concise code, but there is a performance advantage to Lambdas over anonymous classes, because Lambdas are implemented using Java’s Invoke Dynamic mechanism (though I suspect the difference to be negligible in the vast majority of cases – one for richardstartin.uk to benchmark?).
Closures: When an anonymous function refers to values outside it’s scope, we say it encloses those variables, i.e., it is a Closure. In Java, a Lambda expression can only reference (enclose) final or effectively-final variables, but since these can refer to heap objects, we can make a Java Lambda Expression act like a Closure. If I want to enclose a non-final stack variable, I usually just put it in an array of length 1 – not pretty, but it works.