Book Image

Learning Java Lambdas

By : Toby Weston
Book Image

Learning Java Lambdas

By: Toby Weston

Overview of this book

In this short book, we take an in-depth look at lambdas in Java, and their supporting features. The book covers essential topics, such as functional interfaces and type inference, and the key differences between lambdas and closures. You will learn about the background to functional programming and lambdas, before moving on to understanding the basic syntax of lambdas and what differentiates these anonymous functions from standard anonymous classes. Lastly, you'll learn how to invoke lambdas and look at the bytecode generated. After reading this book, you'll understand lambdas in depth, their background, syntax, implementation details, and how and when to use them. You'll also have a clear knowledge of the difference between functions and classes, and why that's relevant to lambdas. This knowledge will enable you to appreciate the improvements to type inference that drive a lot of the new features in modern Java, and will increase your understanding of method references and scoping.
Table of Contents (10 chapters)

Exception handling


There's no new syntax for exception handling in lambdas. Exceptions thrown in a lambda are propagated to the caller, just as you'd expect with a regular method call. There's nothing special about calling lambdas or handling their exceptions.

However, there are some subtleties that you need to be aware of. Firstly, as a caller of a lambda, you are potentially unaware of what exceptions might be thrown, if any and secondly, as the author of a lambda, you're potentially unaware what context your lambda will be run in.

When you create a lambda, you typically give up responsibility of how that lambda will be executed to the method that you pass it to. For all you know, your lambda may be run in parallel or at some point in the future and so any exception you throw may not get handled as you might expect. You can't rely on exception handling as a way to control your program's flow.

To demonstrate this, lets write some code to call two things, one after the other. We'll use Runnable...