Type Local variable PLAYER_PREFIX defined in an enclosing scope must be final or effectively final

Hi I don’t know what this means, could you help me please?

My code:

@Listener
public void onPlayerJoinEvent(ClientConnectionEvent.Join event) {
Player player = event.getTargetEntity();

TabList tablist = player.getTabList();

tablist.setHeader(Text.of(config.getNode("tablist", "text", "header").getString()));
tablist.setFooter(Text.of(config.getNode("tablist", "text", "footer").getString()));

String PLAYER_NAME = (player.getName());

String PLAYER_PREFIX = "";

if (config.getNode("tablist", "prefix", "enable").getBoolean()) {
	
	if (player.hasPermission("stac.handler.1")) {
		PLAYER_PREFIX = (config.getNode("tablist", "prefix", "1").getString());
	} 
	else if (player.hasPermission("stac.handler.2")) {
		PLAYER_PREFIX = (config.getNode("tablist", "prefix", "2").getString());
	} 
	else if (player.hasPermission("stac.handler.3")) {
		PLAYER_PREFIX = (config.getNode("tablist", "prefix", "3").getString());
	} 
	else if (player.hasPermission("stac.handler.4")) {
		PLAYER_PREFIX = (config.getNode("tablist", "prefix", "4").getString());
	} else {
	}
}

Sponge.getServer().getOnlinePlayers().stream().forEach(p -> {
    Optional<TabListEntry> opEntry = tablist.getEntry(p.getUniqueId());
    if(!opEntry.isPresent()){
        return;
    }
    opEntry.get().setDisplayName(Text.of(PLAYER_PREFIX + PLAYER_NAME + "[Suffix]"));
});

}

please do yourself a favour and don use lambdas for forEach in java. Java does not have a functional context like JavaScript which makes it rather useless imho.
instead use for (Player p : Sponge.getServer().getOnlinePlayers())

2 Likes

So what it means is you are talking to a variable in a nested (or nested like class - in this case the lamda expression) that isnt set to final or still acts as a final variable.

You have 2 options. The first is to put the variables outside the function, making it a field variable. The other option is to create another variable just before the lamda and set that new variable as the variables before.

Please note that these are java specific issues and I would advise understanding java before you takle the sponge api.

2 Likes