I'm pretty new to scala and basically I want to have a couple of functions coupled to a string in a hashmap. However I get an error at subscribers.get(e.key)(e.EventArgs); stating Option[EventArgs => Unit] does not take parameters... Example code:
object Monitor {
    val subscribers = HashMap.empty[String, (EventArgs) => Unit ]
    def trigger(e : Event){
      subscribers.get(e.key)(e.EventArgs);
    }
    def subscribe(key: String, e: (EventArgs) => Unit) {
      subscribers += key -> e;
    }
}
                The get method of a Map gives you an Option of the value, not the value. Thus, if the key if found in the map, you get Some(value), if not, you get None. So you need to first "unroll" that option to make sure there is actually a value of a function which you can invoke (call apply on):
def trigger(e: Event): Unit =
  subscribers.get(e.key).foreach(_.apply(e.EventArgs))
or
def trigger(e: Event): Unit =
  subscribers.get(e.key) match {
    case Some(value) => value(e.EventArgs)
    case None =>
  }
There are many posts around explaining Scala's Option type. For example this one or this one.
Also note Luigi's remark about using an immutable map (the default Map) with a var instead.
Since the get method returns Option, you can use 'map' on that:
subscribers.get(e.key).map(f => f(e.EventArgs))
or even shorter:
subscribers.get(e.key) map (_(e.EventArgs))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With