Last active
January 19, 2022 21:23
-
-
Save stefanofago73/06d0ca844ed3f109d1be4879a9b22561 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//==================================== | |
// | |
// 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