Open jubax opened 4 hours ago
I'll take a look.
I have never programmed with records so a naive question. Does a record with no data make sense ? Are there valid use cases for such ??
I'll take a look.
I have never programmed with records so a naive question. Does a record with no data make sense ? Are there valid use cases for such ??
Yes, it is useful for more functional-style result values. E.g. consider
ParseLogFileResult parseLogFileAndExtractErrorLevelMessages(File file) {}
sealed interface ParseLogFileResult {
record Success(List<String> messagesWithErrorLevel) implements ParseLogFileResult {}
record NotApplicable_FileDoesNotExist() {}
record NotApplicable_InvalidLogFileFormat() {}
record Failure(Exception exception) {}
}
So we are using records as markers here.
Oftopic: why not use enums instead?
Oftopic: why not use enums instead?
Because enums are static. But in the example above I want to return the actual values. With the structure above I can write
sealed interface ParseLogFileResult {
record Success(List<String> messagesWithErrorLevel) implements ParseLogFileResult {}
record NotApplicable_FileDoesNotExist() implements ParseLogFileResult {}
record NotApplicable_InvalidLogFileFormat() implements ParseLogFileResult {}
record Failure(Exception exception) implements ParseLogFileResult {}
}
ParseLogFileResult parseLogFileAndExtractErrorLevelMessages(File file) {
return new ParseLogFileResult.Success(List.of("a", "b"));
}
public void test() {
ParseLogFileResult result = parseLogFileAndExtractErrorLevelMessages(new File("x.log"));
switch (result) {
case ParseLogFileResult.Success(List<String> messagesWithErrorLevel) -> {
System.out.println(messagesWithErrorLevel);
}
case ParseLogFileResult.NotApplicable_FileDoesNotExist() -> {}
case ParseLogFileResult.NotApplicable_InvalidLogFileFormat() -> {}
case ParseLogFileResult.Failure(Exception ex) -> { ex.printStackTrace(); }
}
}
Thanks for the example. Thought provoking (at least for me.)
When you have
Then you get the "empty block" warning for the seconds record (probably because the record has no parameters):
This warning should not be shown.