use()
use()
looks and works a lot like let()
, with two major differences.
First, you cannot call use()
on any object. It has to be something that implements the Java Closeable
interface. This interface, added in Java 5, represents some resource that can be closed, such as a stream or socket.
Second, after executing your block of code, use()
calls close()
on that Closeable
. It will do this even if your block throws an exception, by means of using a try
/finally
structure. Hence, by using use()
, you know that whatever this resource is will be properly closed.
In summary, use()
:
- Is called on some object that implements the
Closeable
interface - Takes whatever you call it on and passes that into the lambda expression as a parameter
- Returns whatever the last statement of the lambda expression evaluates to
- Calls
close()
on theCloseable
object
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.