Created
August 26, 2018 18:18
-
-
Save namuan/0131dbb442187730ce17b3058d5f42de to your computer and use it in GitHub Desktop.
[Combinators] Since Java 8 `static` and `default` methods are allowed within `interface`s.
This file contains hidden or 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
interface ArtistValidator extends Function<Artist, Optional<Artist>>{ | |
static ArtistValidator hasMailWithAtSign(){ | |
return holds(artist -> artist.email.contains("@")); | |
} | |
static ArtistValidator nameIsNotEmpty(){ | |
return holds(artist -> artist.name.trim().length()>0); | |
} | |
static ArtistValidator holds(Function<Artist, Boolean> p){ | |
return artist -> p.apply(artist)?Optional.of(artist):Optional.empty(); | |
} | |
default ArtistValidator and(ArtistValidator other){ | |
return artist -> apply(artist).flatMap(other); | |
} | |
} | |
ArtistValidator validator = nameIsNotEmpty().and(hasMailWithAtSign()); | |
validator.apply(new Artist("Lenzman", "[email protected]")); // valid | |
validator.apply(new Artist("", "[email protected]")); // invalid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment