Chapter 4. Libraries
I’ve talked about how to write lambda expressions but so far haven’t covered the other side of the fence: how to use them. This lesson is important even if you’re not writing a heavily functional library like streams. Even the simplest application is still likely to have application code that could benefit from code as data.
Another Java 8 change that has altered the way that we need to think about
libraries is the introduction of default methods and static methods on
interfaces. This change means that methods on interfaces can now have bodies
and contain code.
I’ll also fill in some gaps in this chapter, covering topics such as what happens when you overload methods with lambda expressions and how to use primitives. These are important things to be aware of when you’re writing lambda-enabled code.
Using Lambda Expressions in Code
In Chapter 2, I described how a lambda expression is given the type of a functional interface and how this type is inferred. From the point of view of code calling the lambda expression, you can treat it identically to calling a method on an interface.
Let’s look at a concrete example framed in terms of logging frameworks. Several
commonly used Java logging frameworks, including slf4j and log4j, have methods
that log output only when their logging level is set to a certain level or higher. So, they
will have a method like void debug(String message) that will log message
if the level is at debug.
Unfortunately, calculating the message to ...