useAll

inline fun <T, R : AutoCloseable> Collection<R>.useAll(block: (List<R>) -> T): T

Executes the given block with all elements of this Collection of AutoCloseable resources, ensuring that all resources are closed after the block completes, even if an exception is thrown.

This function is useful for safely working with multiple resources that need to be closed, such as streams or files, in a single operation.

Return

The result of the block.

Parameters

block

The function to execute with the list of resources. The resources are provided as a List.

Throws

If the block throws an exception, it will be rethrown after all resources are closed. Any exceptions thrown during closing are suppressed and attached to the original exception.

Usage example:

val resources: List<MyResource> = ...
val result = resources.useAll { list ->
// Use all resources in 'list'
}
// All resources are now closed