Example of Scala's "call be name":
def giveMeName(b: => String)
Java result:
public class some.package.CallByNameEx {
public void giveMeName(scala.Function0<java.lang.String>);
public some.package.CallByNameEx();
}
Example of Java's Functional Interface API:
void giveMeName(Supplier<String> b)
Java result:
public class some.package.SupplyEx {
public some.package.SupplyEx();
void giveMeName(java.util.function.Supplier<java.lang.String>);
}
Is there any major difference in how they get evaluated internally considering the javap result of both the above cases were almost identical
As per my current understanding, they both sort of use closures and evaluates the expression lazily. Please correct me if the understanding is wrong.
You got it right, the
call-by-namesyntax is pretty much a shorthand allowing you to avoid the additional bureaucracy of dealing with passing aFunction0around.Internally,
b: => Stringwill be represented byFunction0- just likeb: () => Stringwould be.The difference is that by using the
call-by-name, you can simply ignore the implementation detail of usingFunction0.Let's see how it would look like with
b: () => String:and the same again using
call-by-name:Pay attention to how nicely the boilerplate
apply()call can be avoided.So, it's a syntactic sugar, but not for Java's Functional Interfaces, but for Scala's native
Function0I wrote a bit more about that here: http://4comprehension.com/leveraging-lambda-expressions-for-lazy-evaluation-in-java/