Whilst you could already use Bukkit's native event api, I added an event api specificly for ScalaPlugins that aims to be cleaner. Here are its features.
- extend xyz.janboerman.scalaloader.event.Event without having to provide the HandlerList boilerplate (of course you still can if you want).
- implement xyz.janboerman.scalaloader.event.Cancellable without having to provide isCancelled and setCancelled methods (of course you still can if you want).
- A a more type-safe version of PluginManager#registerEvent. The EventExecutor is type-constrained to the event that is being listenend on.
- Access the event bus right from your ScalaPlugin's main class, no need to call #getServer#getPluginManager, just call #getEventBus
- EventBus#callEvent returns a boolean - indicating whether the event is allowed to happen - always true for non-cancellable events.
All ScalaPlugin classes that use xyz.janboerman.scalaloader.event.{Event, Cancellable, EventExecutor} are transformed at class-load time to use their bukkit counterparts. Because of the way this works, JavaPlugins do not get the transformations - meaning they cannot use these types AT ALL, but using subtypes defined in ScalaPlugins will work just fine.
Some example code (also available on
github):
Code (Scala):
//event definition
import org.
bukkit.
entity.
Player
import org.
bukkit.
Location
import xyz.
janboerman.
scalaloader.
event.
{Cancellable, Event
}
case
class HomeTeleportEvent
(player
: Player, home
: Location
)
extends Event
with Cancellable
Code (Scala):
//code that executes the event
if
(ExamplePlugin.
getEventBus.
callEvent
(HomeTeleportEvent
(player, home
)
)
)
{
player.
teleport
(home
)
player.
sendMessage
(
"Welcome home!"
)
;
}
else
{
player.
sendMessage
(
"Some plugin prevented you from teleporting to your home!"
)
}
Code (Scala):
//event listener
import org.
bukkit.
event.
{EventHandler, Listener
}
object RandomHomeTeleportBlocker
extends Listener
{
@EventHandler
def onTeleportHome
(event
: HomeTeleportEvent
)
: Unit
=
{
event.
setCancelled
(Math.
random
(
)
<
0.5
)
;
}
}
That's it, happy Scala coding!