Skip to content

Instantly share code, notes, and snippets.

@kijanowski
Last active November 4, 2018 19:16
Show Gist options
  • Save kijanowski/5fd155548b8512c078b473428dc96076 to your computer and use it in GitHub Desktop.
Save kijanowski/5fd155548b8512c078b473428dc96076 to your computer and use it in GitHub Desktop.
nestedConditionsWithReturn
// instead of
public String legacyNestedConditionsWithReturn(String nullableValue) {
if (nullableValue == null) {
return DEFAULT;
} else if (nullableValue.startsWith("ONE")) {
return nullableValue.concat("123");
} else if (nullableValue.startsWith("TWO")) {
return nullableValue.concat("456");
} else {
return nullableValue.concat("789");
}
}
// do it the functional way
public String vavrNestedConditionsWithReturn(String nullableValue) {
return Match(Option.of(nullableValue)).of(
Case($None(), () -> DEFAULT),
Case($Some($(v -> v.startsWith("ONE"))), () -> nullableValue.concat("123")),
Case($Some($(v -> v.startsWith("TWO"))), () -> nullableValue.concat("456")),
Case($Some($()), () -> nullableValue.concat("789"))
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment