Best way to check if optional is present

Hello,
I want a tip. What is the best (or correct) way to check if a optional is present on a event?

...
//this
event.getCause().first(Player.class).isPresent;
//or this
event.getCause().containsType(Player.class);
...

Either way works fine, it’s really up to personal opinion.

I prefer the first way, just calling first, because you’re using the same method every time, but containsType seems more readable.

My preference is public void onDoSomething(SomethingEvent event, @First Player p)

Good point to see.

If i use “@First Player p” on event method, i dont need to check if the player optional is present? Or in other words, the event will only fire if the cause have the type Player class?

I using this on my code:

        @Listener
	public void onBucketUse(UseItemStackEvent event){
            if (event.isCancelled() || !event.getCause().first(Player.class).isPresent()) {
                 return;
            }
        Player p = event.getCause().first(Entity.class).get();
        ...
        }

I can replace by this?

        @Listener
	public void onBucketUse(UseItemStackEvent event, @First Player p) {
            if (event.isCancelled()) {
                 return;
            }
	...
	}

Yes, that’s it exactly.

1 Like

Actually, you can further simplify it to this:

        @Listener
        @IsCancelled(Tristate.FALSE) //I believe this is default
	public void onBucketUse(UseItemStackEvent event, @First Player p) {
	        ...
	}

I check if is cancelled because Bukkit server still pass the event to other listeners if is cancelled, but i dont know if Sponge still passing the cancelled event or not to other listeners.

But i will use this anottation, its really simply :slight_smile:

They don’t actually. Sponge events are not passed by default if they are cancelled, however you can change this with @IsCancelled.