Example of contravariance

I am thinking of the following example to illustrate why contravariance is useful.

Let's consider a GUI framework with Widgets, Events, and Event Listeners.

abstract class Event;
class KeyEvent extends Event
class MouseEvent extends Event

trait EventListener[-E] { def listen(e:E) }

Let Widgets define the following methods:

def addKeyEventListener(listener:EventListener[KeyEvent])
def addMouseEventListener(listener:EventListener[MouseEvent])

These methods accept only "specific" event listeners, which is fine. However I would like to define also "kitchen-sink" listeners, which listen to all events, and pass such listeners to the "add listener" methods above.

For instance, I would like to define LogEventListener to log all incoming events

class LogEventListener extends EventListener[Event] {
   def listen(e:Event) { log(event) }
}

Since the trait EventListener is contravariant in Event we can pass LogEventListener to all those "add listener" methods without losing their type safety.

Does it make sense ?

29
задан Michael 19 March 2011 в 17:01
поделиться