Search code examples
scalapartialfunction

Missing parameter type in applyOrElse Scala


I have this code where I'm trying to call a partial function. When I build my project I get an error stating missing parameter type ++ headerExtractor.applyOrElse(event, _ => Map.empty).

I've looked at other posts, but I feel like this should be working. What am I doing wrong?

I'm calling headerExtractor here

private def publishToProfileExchange(customer: Schema.Customer, event: Schema.CustomerEvent): Future[Done] = {
  val messageType: String = "ProfileEvent"
  val headers: Map[String, AnyRef] = Map(
    "profileId" -> customer.id.toString,
    "eventType" -> event.eventType,
    "type" -> messageType
  ) ++ headerExtractor.applyOrElse(event, _ => Map.empty)

  ...
  //valid return values would be here
}

private val headerExtractor: PartialFunction[Schema.CustomerEvent, Map[String, AnyRef]] = {
    case x if x.eventType.equalsIgnoreCase("message") && (x.eventData \ "incoming").asOpt[Boolean].getOrElse(false) =>
       Map("incomingMessage" -> "true")
}

Solution

  • you have to provide the type of paramater on your .applyOrElse(). See example below

    case class CustomerEvent(eventType: String, eventData: String)
    
    val headerExtractor = new PartialFunction[CustomerEvent, Map[String, AnyRef]] {
      def apply(x: CustomerEvent): Map[String, AnyRef] = Map("incomingMessage" -> "true")
      def isDefinedAt(x: CustomerEvent): Boolean = x.eventType.equalsIgnoreCase("message")
    }
    
    assert(headerExtractor.applyOrElse(CustomerEvent("message", "{}"), (customerEvent: CustomerEvent) => Map.empty)
      == Map("incomingMessage" -> "true"))
    
    // or simply do (_: CustomerEvent)
    
    assert(headerExtractor.applyOrElse(CustomerEvent("message", "{}"), (_: CustomerEvent) => Map.empty)
          == Map("incomingMessage" -> "true"))
    

    negative case

    assert(headerExtractor.applyOrElse(CustomerEvent("something-else", "{}"), (_: CustomerEvent) => Map.empty) 
    == Map())