I am currently attempting to write a generalization of dialogue routines for my game (currently, every npc character has their own class where i have to hardcode in a bunch of if-else statements)
to do so, I am writing a class DialogueTree which represents the dialogue. A dialogue tree is made up of Nodes which contain many fields, but the important one here is a BiPredicate 'req', which represents the requirements (stat, quest etc) of the player and npc for the player to go down this dialogue path. Here is the code for all of that so far.
public class DialogueTree implements Serializable {
private Node head;
public DialogueTree() {
head = new Node((p,q) -> true);
}
public DialogueTree add(int[] path, BiPredicate<Player,NPC> req) {
head.children.add(new Node(req));
return this;
}
private static class Node implements Serializable {
public List<Node> children;
public BiPredicate<Player,NPC> req;
public Node(BiPredicate<Player,NPC> req) {
this.req = req;
}
}
}
i left out a lot of the code because i don't want to distract with irrelevant details, but the main thing i wanna highlight is that when constructing these DialogueTrees i'm passing in lambda expressions (the whole reason im doing this is so I don't have to write a new class for every single NPC's dialogue, so I don't want to write a class for a specific requirement that implements BiPredicate and Serializable)
the issue is have is when i start the game and try to save, the game crashes with an error citing the lambda expression as non-serializable. i tried casting req to serializable within the Node constructor
this.req = (BiPredicate<Player,NPC> & Serializable)req;
however that got me a class cast exception.
any help is greatly appreciate :D
The cast is failing because the BiPredicate was already instantiated with a non-Serializable lambda. To make it serializable, you need to cast the lambda expression itself:
head = new Node((BiPredicate<Player,NPC> & Serializable)(p,q) -> true);