java lambda expression under the hood – phrasebook

Q: how are java8 lambda expressions translated?

* Special helper method – InvokeDynamic. You can see it in the bytecode
* Static methods – a non-capturing (stateless) lambda expression is simply converted to a static method
* a capturing lambda expression can also become a static method with the captures as additional method args. This may not be the actual compiler action, but it is a proven model. (Compare : separate chaining is one proven implementation of hash tables.)

However, static methods obscure an essential rule — the lambda expression’s type must “look like” a subtype of a SAM interface. Remember you often pass a lambda around as if it’s a SAM (subtype) instance.

So even if the number crunching is done in a static method, there must be some non-static wrapper method in a SAM subtype instance.

(more pure)SAM^functional interface]java

Most experts and authors on the internet don’t differentiate the 2. [[functional thinking]] says that a java 8 functional interface can have default methods in addition to a SAM (single abstract method)

Later, I will probably add a bit more details, but this is the key message.

Q: is a lambda related to SAM or FI (with default methods)? Official answer seems to be FI but can a FI-with-default-methods?

delegate: Yamaha makes motorbikes + pianos

label: lambda/delegate
when we say “delegate” we should but don't make an explicit distinction between a delegate typename vs a delegate instance.
Also, we seldom make an explicit distinction between the multicast delegate and unicast delegate usages, but these 2 have too little overlap to be discussed as the same concept. 
Yamaha makes motorbikes + pianos

lambda – final local var — rationales, loopholes

Possibly a popular interview question…..

For Both lambda and inner classes to use a given variable:

A) local vars in enclosing method must be (as of Java 8, "effectively") final
** subversion / loophole — a final local variable in the form of "array of 1" would let the lambda to modify the content
**** similarly, you can provide a wrapper object, who is a final local variable but not immutable.
B) enclosing Class instance fields don’t need finality to be usable in lambda.

The most important motivation for the (effective) finality restriction is thread safety. For (B), this restriction is impractical.

Incidentally (perhaps another post), in java 8, you lambda is compiled not as an inner class, but as a static method with a special helper class.

c# delegates – 2 fundamental categories

Update: java 8 lambda. [[mastering lambds]] P 5 mentions AA BB DD as use cases for Command pattern

AA — is the main topic of the book
BB — https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
DD — http://www.oracle.com/technetwork/articles/java/lambda-1984522.html and http://www.drdobbs.com/jvm/jdk-getting-a-head-start-with-lambdas/240008174

Today I finally feel ready to summarize the 2 usage categories of c# delegates. If you are new like me, it’s better to treat them as 2 unrelated constructs. Between them, the underlying technical similarities are relevant only during initial deep dive, and become less important as you see them in various patterns (or “designs”).

In java, these features are probably achieved using interface + other constructs. Dotnet supports interfaces too, but in some contexts offers more “specialized” constructs in the form of delegates. As shown below, in such a context interfaces are usable but less than delegates.

Most tutorials would start with unicast delegate, without the inv list.

Coming from a java or c++ background, you will want to find a counterpart or close equivalent to delegates. Almost hopeless for BB. For AA there are quite a few, which adds to the confusion.

AA) lambda as function AAArgument
* I believe compiler converts such a lambda into a STATIC method (there’s really no host object) then bind it to a delegate Instance
* often returns something
* Usually _stateless_, usually without captured variables.
* predominantly unicast
* Action, Func and Predicate are often used in this context, but you can also use these 3 constructs as closures, which is a 3rd category beyond AA and BB
* Domain? Linq; functor argument as per Rajesh of OC
* Before java 8, often implemented as an interface or an anonymous inner class

BB) event field Backed by a multicast delegate instance (See other posts on “newsletter”)
* Usually NON-STATIC methods, esp. in GUI context
* Usually returns void
* A callback method is usually _stateful_, because the callback method often does its job with “self-owned” i.e. this.someField objects, beyond the argument objects passed in
* event is a pseudo _f i e l d_ in a class. Static field or non-static field are both common.
* Domain? GUI + asynchronous WCF
* we must register the callback method with the event source.
** can lead to memory leak
* in java, implemented by several callback Objects supporting a common interface (cf swing)


Some of the other categories —
CC) CCClosure — stateful, seldom passed in as a func arg
DD) thread start
EE) Passing in a delegate instance as a function input is the lambda usage (AA). How about returning from a function? P83 [[c#precisely]] shows examples to return an anon delegate instance. This is an advanced and non-trivial unicast use case. The underlying anon method is usually static and stateless

In a source code with AA, we see lots of custom delegate Types created on the fly.

In a source code with BB, delegate Instances take center stage, since each instance is assigned to a … pseudo field. The delegate type is less complicated.

lambda meets template

In cpp, java and c#, The worst part of lambda is the integration with (parametrized) templates.

In each case, We need to understand the base technology and how that integrates with templates, otherwise you will be lost. The base technologies are (see post on “lambda – replicable”)
– delegate
– anon nested class
– functor

Syntax is bad but not the worst. Don’t get bogged down there.

lambda is more industry-standard than delegate

Before java and c++ introduced lambada, I thought delegate is the foundation of lambdas.

Now I think lambda is an industry standard, implemented differently in c++ and java. See post on “lambda – replicable”. For python…

Bear in mind
A) the most fundamental, and pure definition of lambda — a function as rvalue, to be passed in as argument to other functions.

B1) the most common usage is sequence processing in c#, java and c++
* c# introduced lambda along with linq
* java introduced lambda along with streams

B2) 2nd common usage is event handler including GUI.

See post on “2 fundamental categories”

c++ parametrized functor – more learning notes

Parametrized Functor (class template) is a standard, recommended construct in c++, with no counterpart in java. C# delegae is conceptually simpler but internally more complex IMO, and represents a big upgrade from c++ functor. Better get some clarity with functor before comparing with delegates.

The most common functor is the simple stateless functor (like a simple lambda). The 2nd common category is the (stateful but) immutable functor. In all cases, the functor is designed for pass-by-value (not by ref or by pointer), cheap to copy, cheap to construct. I see many textbook code samples creating throwaway functor instances.

Example of the 2nd category – P127[[essentialC++]].

A) One mental block is using a simple functor Class as a template type param. This is different from java/c#

B) One mental block is a simple parametrized functor i.e. class template. C++ parametrized functor can take various type params, more “promiscuous” than c#/java.

C) A bigger mental block, combining A+B, is a functor parametrized with another functor Class as a template param. See P186[[EssentialC++]].

This is presented as a simple construct, with about 20 lines of code, but the more I look at it, the more strange it feels. I think this is somwehwat powerful but unpopular and unfamiliar to mainstream developers.

Functional programming in c++?

In java, we write a custom comparitor class rather than a comparitor class Template. We also have the simpler alternative of a Comparable interface, but that’s not very relevant in this discussion. Java 8 lambda — http://www.dreamsyssoft.com/java-8-lambda-tutorial/comparator-tutorial.php