How to define a more concise scala function

327 Views Asked by At

I am using the akka library and supplying a partial function to be implemented by an actor at runtime via a hot swap.

The akka hot swap takes an argument in the form PartialFunction[Any, Unit]. I have defined mine as the following:

class Fake1Reader extends AbstractReader {

  def read: PartialFunction[Any, Unit] = {
    case readingRequest: ReadingRequest => {
      var reading: Reading = new ReadingImpl(readingRequest.getResourceId, "payload",
        Calendar.getInstance.getTime,
      readingRequest.getfrequency, readingRequest.getMappingName,
        readingRequest.getClassificationType,
      readingRequest.getReadingRequestId)
      sendConsumeMessage(reading)
    }
  }
}

so in order to use this function I have to supply a new Fake1Reader().read.

Is there any more concise way of doing this class using apply or extending Function or PartialFunction?

2

There are 2 best solutions below

0
On

As a side note, this reduces the sheer drudgery of repetition:

case readingRequest: ReadingRequest => {
  import readingRequest._
  var reading: Reading = new ReadingImpl(getResourceId, "payload",
    Calendar.getInstance.getTime,
  getfrequency, getMappingName,
    getClassificationType,
  getReadingRequestId)
  sendConsumeMessage(reading)
}
4
On

If your AbstractReader is stateless, you can define object instead of class to avoid unnecessary object creation on every usage,and place your functions there as immutable val's.

Also, companion object akka.actor.Actor defines type Receive as an alias for PartialFunction[Any, Unit], so you can write your partial functions like this:

package foo    
object Fake1Reader extends AbstractReader {
  import akka.actor.Actor._

  val read: Receive = { 
    case readingRequest: ReadingRequest => /* implementation */
  }
}

usage:

import foo.Fake1Reader._

actorRef ! HotSwap(read)