Alex Rivera | Logout

How to get the domain of a Partial Function in Scala?

Asked 2012-03-04T21:14:39.540
8

Is it possible to get the domain of a Partial Function in Scala?

Ex:

    val f: PartialFunction[Int, Unit] = {

      case 1 => println("This is 1")

      case 2 => println("This is 2")

   }

Is there any way to get something like:

    val list = f.getDomain

which would indicate values 1 and 2?

Update: I am trying to build an notification system (event bus). The subscriber will look like this:

    class SomeSubscriber extends Subscriber {

    notifications {

      case LoginEvent(date) => println("Login on " + date)

      case LogoutEvent(date) => println("Logout on " + date)

      case e: Notification[Any] => async {

         println("Other notification: " + e)

         ui {

          println("UI in async! " + e)

         }

       }

     }

   }

In my NotiticationService (the event dispatcher) I want to access the events declared in every 'notifications' block so I can push the notifications to the subscribers. How can I do that?

Thanks in advance.

Edit
Report

1 Answer

11

If you have a collection, and you'd like to know which elements also belong to the domain of f, you can use filter and isDefinedAt like so:

scala> 1 to 10 filter f.isDefinedAt
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2)

This simply checks exhaustively. I don't know if there is any better way.

answered 2012-03-04T22:00:21.577

Your Answer