The record line declares the four fields. The block below it is a compact constructor. It runs whenever a task is created, and checks the values. A blank title, or a bad priority, is rejected. Records can't change, so complete returns a new task, marked done. And to string shows a tick box, and exclamation marks for priority.
Task.javajava
public record Task(int id, String title, int priority, boolean done) { public Task { if (title.isBlank()) throw new IllegalArgumentException("Title can't be empty"); if (priority < 1 || priority > 3) throw new IllegalArgumentException("1-3 only"); } public Task complete() { return new Task(id, title, priority, true); } @Override public String toString() { String box = done ? "[x]" : "[ ]"; return String.format("%2d %s %-3s %s", id, box, "!".repeat(priority), title); }}
We make two tasks, and print them. Complete gives back a done copy, but the original doesn't change. And a blank title is rejected. Run it. Pay rent has three exclamation marks. Water plants is ticked. B itself is still not done. And the blank task is rejected.
Main.javajava
public class Main { public static void main(String[] args) { Task a = new Task(1, "Pay rent", 3, false); Task b = new Task(2, "Water plants", 1, false); System.out.println(a); System.out.println(b.complete()); System.out.println("b itself is still " + b.done()); try { new Task(3, " ", 2, false); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } }}
Output
1 [ ] !!! Pay rent
2 [x] ! Water plants
b itself is still false
Rejected: Title can't be empty
Also uses Task.java
public record Task(int id, String title, int priority, boolean done) { public Task { if (title.isBlank()) throw new IllegalArgumentException("Title can't be empty"); if (priority < 1 || priority > 3) throw new IllegalArgumentException("1-3 only"); } public Task complete() { return new Task(id, title, priority, true); } @Override public String toString() { String box = done ? "[x]" : "[ ]"; return String.format("%2d %s %-3s %s", id, box, "!".repeat(priority), title); }}
Task is a record, with a compact constructor that checks its values. Complete returns a new, finished task. Next, the TaskList class, which holds them all.