Predicate tips
In our example for creating a party system, we ended up having lots of code repetition. In our party creation command, we had the following code:
java
List<Argument<?>> arguments = new ArrayList<>();
// The "create" literal, with a requirement that a player must have a party
arguments.add(new LiteralArgument("create")
.withRequirement(sender -> !partyMembers.containsKey(((Player) sender).getUniqueId()))
);
arguments.add(new StringArgument("partyName"));
And for our party teleportation command, we had the following code:
java
arguments = new ArrayList<>();
arguments.add(new LiteralArgument("tp")
.withRequirement(sender -> partyMembers.containsKey(((Player) sender).getUniqueId()))
);
We can simplify this code by declaring the predicate:
java
Predicate<CommandSender> testIfPlayerHasParty = sender -> {
return partyMembers.containsKey(((Player) sender).getUniqueId());
};
Now, we can use the predicate testIfPlayerHasParty
in our code for creating a party. Since we want to apply the "not" (!
) operator to this predicate, we can use .negate()
to invert the result of our predicate:
java
List<Argument<?>> args = new ArrayList<>();
args.add(new LiteralArgument("create").withRequirement(testIfPlayerHasParty.negate()));
args.add(new StringArgument("partyName"));
And we can use it again for our code for teleporting to party members:
java
args = new ArrayList<>();
args.add(new LiteralArgument("tp").withRequirement(testIfPlayerHasParty));