Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function from hashmap in Scala

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;
    }

}
like image 364
Seba Kerckhof Avatar asked Jan 19 '23 06:01

Seba Kerckhof


2 Answers

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.

like image 70
0__ Avatar answered Jan 25 '23 14:01

0__


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))
like image 39
Marimuthu Madasamy Avatar answered Jan 25 '23 13:01

Marimuthu Madasamy