Skip to content

Instantly share code, notes, and snippets.

@stefanofago73
Last active January 19, 2022 21:23
Show Gist options
  • Save stefanofago73/06d0ca844ed3f109d1be4879a9b22561 to your computer and use it in GitHub Desktop.
Save stefanofago73/06d0ca844ed3f109d1be4879a9b22561 to your computer and use it in GitHub Desktop.
//====================================
//
// MAIN TYPE
//
//====================================
public interface ComposingAutocloseable extends AutoCloseable
{
default void close() {
doClose();
}
void doClose();
static ComposingAutocloseable with(AutoCloseable subject)
{
return ()->
{
try{ subject.close(); }catch(Exception exc)
{
sneakyThows(exc);
};
};
}
default ComposingAutocloseable compose(ComposingAutocloseable other)
{
return ()-> {
close();
other.close();
};
}
}
//====================================
//
// TEST RECORD
//
//====================================
record Pippo(String name) implements AutoCloseable
{
public void close()
{
System.out.printf("%s is closing!\n",name);
}
}
//====================================
//
// USAGE
// ...with some static imports...
//====================================
var uno = new Pippo("uno");
var due = new Pippo("due");
var tre = new Pippo("tre");
try(with(uno)
.compose(with(due))
.compose(with(tre))){}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment