Skip to content

Instantly share code, notes, and snippets.

@tonivade
Last active August 30, 2020 07:43
Show Gist options
  • Save tonivade/285419e60511ed587cf9876843d74820 to your computer and use it in GitHub Desktop.
Save tonivade/285419e60511ed587cf9876843d74820 to your computer and use it in GitHub Desktop.
Pure Functional Java Builder
import static java.util.Objects.requireNonNull;
public class Builder {
public static void main(String[] args) {
User user = User.builder().id(1).name("toni").email("toni@home").build();
System.out.println(user);
}
}
record User(
Integer id,
String name,
String email) {
public User {
requireNonNull(id, "id cannot be null");
requireNonNull(name, "name cannot be null");
requireNonNull(email, "email cannot be null");
}
public static IdStep builder() {
return id -> name -> email -> () -> new User(id, name, email);
}
}
interface IdStep {
NameStep id(int id);
}
interface NameStep {
EmailStep name(String name);
}
interface EmailStep {
UserBuilder email(String email);
}
interface UserBuilder {
User build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment