1
我有以下代码斯卡拉:未绑定通配符类型
import scala.collection.mutable
import scala.reflect.ClassTag
import scala.reflect._
object EventManager {
var handlers: Map[Class[_ <: Event], mutable.Set[EventHandler[_ <: Event]]] = Map()
def registerHandler [A <: Event](handler: EventHandler[A])(implicit tag: ClassTag[A]): Unit = {
val typeParam = tag.runtimeClass.asSubclass(classOf[Event])
handlers.get(tag.runtimeClass.asSubclass(classOf[Event])) match {
case Some(_) => handlers(typeParam) += handler.asInstanceOf[EventHandler[Event]]
case None => handlers += (typeParam -> mutable.Set(handler))
}
}
//Returns true if the event was cancelled, false otherwise
def fireEvent[A <: Event](event: A)(implicit tag: ClassTag[A]): Boolean = {
val typeParam = tag.runtimeClass.asSubclass(classOf[Event])
event match {
case cEvent: CancellableEvent =>
handlers.get(typeParam) match {
case Some(s) =>
s.foreach(handler => if (!cEvent.cancelled) handler.handle(event.asInstanceOf[_ <: Event]))
case None =>
}
//Return if the event was cancelled or not
cEvent.cancelled
case _ =>
handlers.get(typeParam) match {
case Some(s) => s.foreach(_.handle(event.asInstanceOf[_ <: Event]))
case None =>
}
false
}
}
}
trait Event
trait EventHandler[A <: Event]{
def handle(event: A)
}
trait CancellableEvent extends Event{
var cancelled: Boolean = false
}
它的目标是一个简单的事件处理系统,虽然我不能设法弄清楚如何解决这个恼人的错误我得到。
Error:(31, 91) unbound wildcard type
s.foreach(handler => if (!cEvent.cancelled) handler.handle(event.asInstanceOf[_ <: Event]))
我真的不知道我能做些什么来解决这个问题。另外,我从来没有和Scala一起工作过很长时间,所以如果你对如何让我的代码更加习惯自由地有任何建议的话!