on
Registers an event listener for a specific event type using a simplified syntax.
This extension function provides a convenient way to register event handlers without needing to create separate Listener classes. It leverages Kotlin's reified type parameters to automatically determine the event type at compile time, eliminating the need for explicit class references.
The function registers the event with NORMAL priority and does not ignore cancelled events. The handler is executed on the main server thread when the specified event is fired.
Usage Example
class MyPlugin : JavaPlugin() {
override fun onEnable() {
// Register a player join event handler
on<PlayerJoinEvent> { event ->
event.player.sendMessage("Welcome to the server!")
}
// Register a block break event handler
on<BlockBreakEvent> { event ->
if (event.block.type == Material.DIAMOND_ORE) {
event.player.sendMessage("You found diamonds!")
}
}
}
}How It Works
Uses Bukkit's PluginManager to register a dynamic event listener
Creates an anonymous Listener object for registration purposes
Checks event type at runtime and invokes the handler only for matching events
Automatically handles type casting safely
Important Notes
The event handler runs synchronously on the main server thread
Events are registered with EventPriority.NORMAL
Cancelled events are NOT ignored (ignoreCancelled = false)
The handler lambda receives the event instance as a parameter
Type safety is enforced at compile time through reified generics
Receiver
Plugin The plugin instance that will own this event registration. The listener will be automatically unregistered when the plugin is disabled.
Parameters
A lambda function that receives the event and processes it. This function is called each time the event is fired.
Type Parameters
The type of event to listen for (must extend org.bukkit.event.Event)